Can I call APIs in componentWillMount in React?

前端 未结 3 882
遥遥无期
遥遥无期 2020-12-03 00:15

I\'m working on react for last 1 year. The convention which we follow is make an API call in componentDidMount, fetch the data and setState after the data has c

3条回答
  •  借酒劲吻你
    2020-12-03 00:24

    ComponentWillMount

    Now that the props and state are set, we finally enter the realm of Life Cycle methods

    That means React expects state to be available as render function will be called next and code can break if any mentioned state variable is missing which may occur in case of ajax.


    Constructor

    This is the place where you define.

    So Calling an ajax will not update the values of any state as ajax is async and constructor will not wait for response. Ideally, you should use constructor to set default/initial values.


    Ideally these functions should be pure function, only depending on parameters. Bringing ajax brings side effect to function.

    Yes, functions depend on state and using this.setState can bring you such issues (You have set value in state but value is missing in state in next called function).

    This makes code fragile. If your API is really fast, you can pass this value as an argument and in your component, check if this arg is available. If yes, initialise you state with it. If not, set it to default. Also, in success function of ajax, you can check for ref of this component. If it exist, component is rendered and you can call its state using setState or any setter(preferred) function.

    Also remember, when you say API calls are really fast, your server and processing may be at optimum speed, but you can never be sure with network.

提交回复
热议问题