【问题标题】:update state from ajax call on componentdidmount -react从 componentdidmount -react 上的 ajax 调用更新状态
【发布时间】:2018-03-22 15:27:18
【问题描述】:

我需要从 ajax 响应中更新状态变量。我在下面尝试过

componentDidMount() {
   var parent_object=this;
          axios.get('/template.php')
                  .then((result)=> {
                      console.log(result.data);

   parent_object.setState({component_template:result.data})//not updating

                  });

    console.log("here");
    console.log(this.state.component_template);
}

我可以看到 result.data 的数组,但状态变量 component_template 没有更新

我试过了 How to set state of response from axios in reacthttps://daveceddia.com/ajax-requests-in-react/ 但没有运气

【问题讨论】:

    标签: ajax reactjs ecmascript-6


    【解决方案1】:

    react 中的 setState 是异步调用。 setSate 之后的控制台不保证更新的值。

    添加控制台作为 setState 的回调或在渲染方法中作为第一行来检查更新的状态值。

    【讨论】:

      【解决方案2】:

      React setState 是异步的! 您可以在状态值更新后调用回调函数:

      componentDidMount() {
            axios.get('/template.php')
                    .then((result)=> {
                     console.log(result.data);
                      this.setState({component_template:result.data},()=>{
                         console.log(this.state.component_template);
                       })
      
            });
      

      }

      【讨论】:

        【解决方案3】:

        来自docs

        setState() 并不总是立即更新组件。它可能会批量更新或将更新推迟到以后。这使得在调用 setState() 之后立即读取 this.state 是一个潜在的陷阱。相反,请使用 componentDidUpdate 或 setState 回调 (setState(updater, callback)),它们都保证在应用更新后触发。

        因此状态可能会正确更新,但您的 console.log 可能无法读取更新后的值。尝试使用回调,或检查内部 componentDidUpdate

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-01
          • 2017-02-18
          • 2018-07-21
          • 1970-01-01
          • 2017-04-25
          • 2018-07-25
          • 2019-06-23
          • 2020-08-16
          相关资源
          最近更新 更多