我正在努力了解在我的应用中进行API调用的最佳位置在哪里?
我有这样的主要组成部分:
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<Router />
</Provider>
</React.StrictMode>,
document.getElementById('root'),
)
and inside Router
I have all my routes. some of my other pages require making API calls to a server to get information so im wondering where the best place/best design would be to put these?
I have a component called PageOne
and in there I make an API call on mount to retrieve some data and then add it to my redux state. but I also need the same data in my PageTwo
component. obviously if the user goes via PageOne
> PageTwo
this is fine because that data is in the redux store so I just grab it. but im wondering if they went directly to PageTwo
or refreshed the page whilst on PageTwo
. that data would no longer be fetched.
所以我的选择就像:
- fetch the data again on
PageTwo
. but this seems like I could be making a lot of requests (plus unnecessary requests as I might be fetching when I already have it) - can I put the fetch inside the router component? I guess this would always trigger no matter what page I went too. but again I would be doing unnecessary requests potentially
是否有任何“好的” /最佳实践方法来处理此问题?