Where to place logic for loading initial server data in React app?

前端 未结 2 656
青春惊慌失措
青春惊慌失措 2021-01-18 13:42

I am using React-Redux to build an application.

To load initial data for a React smart component, I need to dispatch a Redux action where the server data r

相关标签:
2条回答
  • 2021-01-18 14:07

    The recommended way is, I believe, to do it in componentDidMount. See this for more info.

    0 讨论(0)
  • 2021-01-18 14:26

    Edit: Dan Abramov recently stated

    In future versions of React we expect that componentWillMount will fire more than once in some cases, so you should use componentDidMount for network requests.


    In componentDidMount

    Read here.

    Fetch data in componentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.

    When fetching data asynchronously, use componentWillUnmount to cancel any outstanding requests before the component is unmounted.

    Documentation is really scarce on "why in componentDidMount". I believe componentWillMount is not called if you use server-side render, so this could be a reason why componentDidMount is preferred.

    0 讨论(0)
提交回复
热议问题