Can I call APIs in componentWillMount in React?

前端 未结 3 876
遥遥无期
遥遥无期 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.

    0 讨论(0)
  • If you need just data only at first run and if you are ok with that. You can setState synchronously via calling a callback.

    for eg:

    componentWillMount(){
        this.setState({
                    sessionId: sessionId,                
                }, () => {
                    if (this.state.hasMoreItems = true) {
                        this.loadItems()   // do what you like here synchronously 
                    }
                });
    }
    
    0 讨论(0)
  • 2020-12-03 00:41

    1. componentWillMount and re-rendering

    Compare this two componentWillMount methods.
    One causes additional re-render, one does not

    componentWillMount () {
      // This will not cause additional re-render
      this.setState({ name: 'Andrej '});
    }
    
    componentWillMount () {
      fetch('http://whatever/profile').then(() => {
        // This in the other hand will cause additional rerender,
        // since fetch is async and state is set after request completes.
        this.setState({ name: 'Andrej '});
      })
    }
    

    .
    .
    .
    2. Where to invoke API calls?

    componentWillMount () {
      // Is triggered on server and on client as well.
      // Server won't wait for completion though, nor will be able to trigger re-render
      // for client.
      fetch('...')
    }
    
    componentDidMount () {
      // Is triggered on client, but never on server.
      // This is a good place to invoke API calls.
      fetch('...')
    } 
    

    If you are rendering on server and your component does need data for rendering, you should fetch (and wait for completion) outside of component and pass data thru props and render component to string afterwards.

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