Setting state on componentDidMount()

后端 未结 3 1834
轮回少年
轮回少年 2020-12-04 12:17

I know that it is an anti-pattern to set state on componentDidMount and a state should be set on componentWillMount but suppose I want to set the l

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 12:32

    It is not an anti-pattern to call setState in componentDidMount. In fact, ReactJS provides an example of this in their documentation:

    You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.

    Example From Doc

    componentDidMount() {
        fetch("https://api.example.com/items")
          .then(res => res.json())
          .then(
            (result) => {
              this.setState({
                isLoaded: true,
                items: result.items
              });
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }
    

提交回复
热议问题