Can't perform a React state update on an unmounted component?

后端 未结 2 1950
悲哀的现实
悲哀的现实 2021-01-22 06:19

I am fetching data in componentDidMount and updating the state and the famous warning is appearing:

Can\'t perform a React state update on an unmounted co

2条回答
  •  花落未央
    2021-01-22 07:14

    Your question is the same as the following question.

    How the component is developed, you can enter a loop and execute the render infinitely. To prevent it, add one more state and control to make the request only 1 time or those that need but that are "mindful".

    Also, your code needs some changes, you can use the State to validate whether to show something or not and once the request is made, set the state again. With some change your code can look like this:

    state = {
        loadingData: true,
        post: null
    }
    
    render() {
        if (!this.state.loadingData) {
            return (
                

    {this.state.post.postTitle}

    {this.state.post.postBody}

    ); } else { return } } componentDidMount() { this._isMounted = true; if(this.state.loadingData) axios .get('https://jsonplaceholder.typicode.com/posts/' + + this.props.postId) .then((response) => { this.setState({ loadingData: false, post: { id: response.data.id, postTitle: response.data.title, postBody: response.data.body } }) }) .catch((e) => { console.log('error', e) }) }

    I hope it's useful. Regards

提交回复
热议问题