繁体   English   中英

setState 未更新 React 组件 state

[英]setState not updating React component state

我在组件的构造函数中有以下内容:

constructor(props){
        super(props);
        this.state={
            post: {},
            deleteModal: false
        }
    }

我在 componentDidmount 中更新 state,如下所示:

componentDidMount(){
        fetch('https://snaptok.herokuapp.com/fetchPost/'+this.props.postId,{
            method: 'GET'
        }).then(response => {
            if (response.ok) {
              return response;
            } else {
              var error = new Error('Error ' + response.status + ': ' + response.statusText);
              error.response = response;
              throw error;
            }
          },
          error => {
                throw error;
          }).then(res=>res.json()).then(res=>this.setState({
              post: res
          })).catch(err=>{console.log(err);})
    }

这是水库 object:

{"_id":"60c0ac493175c10014e178d4","author":"Vipul Tyagi","email":"vipultyagi629@gmail.com","uid":"0FGD6CWHi6YnaE7an0MW0z9yk7p1","title":"This is a title","description":"This is a description.","file":"","fileType":"","subGratis":"Cricket","dateOfPost":"9-6-2021","likes":0,"comments":[],"__v":0}

但是在渲染方法中, this.state.post仍然是{} 我可以确认 res 不是空对象(我已在网络选项卡中签入)。 我不知道我的代码有什么问题,设置空 object 的 state 是否正确。

请帮助我纠正我的代码中的错误(如果有)。 谢谢你。

编辑:我将 componentWillUnmount 放在上面的组件中,发现该组件无缘无故被卸载。 然后它不会再次安装。

我预计问题出在 function 上下文中this

也许你可以尝试这样:

componentDidMount(){
    const setState = this.setState;
    fetch('https://snaptok.herokuapp.com/fetchPost/'+this.props.postId,{
        method: 'GET'
    }).then(response => {
        if (response.ok) {
          return response;
        } else {
          var error = new Error('Error ' + response.status + ': ' + response.statusText);
          error.response = response;
          throw error;
        }
      },
      error => {
            throw error;
      }).then(res=>res.json()).then(res=>setState({
          post: res
      })).catch(err=>{console.log(err);})
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM