简体   繁体   中英

setState not updating React component state

I have below in component's constructor:

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

I am updating the state as below in componentDidmount:

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);})
    }

This is the res 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}

But in the render method, this.state.post is still {} . I can confirm that res is not empty object( I have checked in network tab). I don't know what is the problem in my code, is it the right way to set state of an empty object.

Please help me to correct the error, if any, in my code. Thank You.

EDIT : I put componentWillUnmount in the above component and found that this component is getting unmounted for no reason. And then it is not getting mounted again.

I expect that the problem is in function context this .

May be you can try such that:

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);})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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