简体   繁体   English

React-setState(…)只能更新已安装或正在安装的组件

[英]React - setState(…) Can only update a mounted or mounting component

I'm new to React and for the first time I have stumbled upon the following error message: 我是React的新手,这是我第一次偶然发现以下错误消息:

Warning: setState(...) Can only update a mounted or mounting component. 警告:setState(...)只能更新已安装或正在安装的组件。 This usually means you called setState() on an unmounted component. 这通常意味着您在未安装的组件上调用了setState()。 This is a no-op. 这是无人值守。 Please check the code for the Comment component. 请检查注释组件的代码。

I'm trying to understand what the message is telling me but every time I re-shuffle my code I still get the same error message repeating about 50 times per second in my console although the components do render as they should. 我试图理解该消息告诉我的内容,但每次重新调整代码时,尽管组件确实按应有的方式呈现,但我仍然在控制台中收到相同的错误消息,每秒重复执行约50次。 Here are the components: 以下是组件:

App.js App.js

import React, { Component } from 'react';
import $ from 'jquery';
import Commentspar from './Components/commentspar';

class App extends Component {
    constructor(props) {
        super(props);    
        this.state = {
            commentsLoading:"loading",
            commentsPre:[],
            upToId:0,
            comments:[]
        }
    }

commentsXMLrequest = () => {

    this.setState({
        commentsLoading:"loading"
    })

       //the below ajax call goes and retrieves the data to fill my components through state
      $.ajax({  
        type: "GET",  
        dataType: "json",  
        crossDomain:true,  
        url:"http://someendpoint.com/endpoint.php",
        success: function(data){

           var parsedComments = JSON.parse(data);  
           var newComments = [/* just above here I construct an array of new objects that look something like {id:0,text:"blah blah",type:"sad"} */];

                // here I populate the commentsPre array with the new array of objects
                this.setState({
                    commentsPre:newComments,
                    commentsLoading:""
                })   

            // here I call the next function (this is the one I would like to repeat)
            this.commentsShow()

        }.bind(this)
    })     
}


commentsShow = () => {

    var newId = this.state.upToId;
    // the newArray variable below is set to select which comment to show in the commentsPre array and increments every time the commentsShow function runs
    var newArray = [this.state.commentsPre[newId]];

    this.setState({
        comments:newArray,
        upToId:this.state.upToId + 1 //incrementation here
    })

    setTimeout(function(){
        // here is where i'm trying to repeat this function every second after incrementing the upToId state but it gives me the error
        this.commentsShow()
    }.bind(this),1000)
}

 componentDidMount() {       

     //initially kick of the load data function when page is loaded
     this.commentsXMLrequest()

}

render() {      

return (
    <div className="App">
        <div className="app-content-wrap">
            <div className="app-content-wrap-inner">

            <Commentspar commentsPre={this.state.commentsPre} commentsShow={this.commentsShow} commentsLoading={this.state.commentsLoading} comments={this.state.comments} />              

            </div>
        </div>    
  </div>
);
}
}

commentspar.js commentspar.js

import React, {Component} from 'react';
import Comment from'./comment';

class Commentspar extends Component { 

    render() {
        return (
            <div className="comments-par">
                <div className={"comments-inner " + this.props.commentsLoading}>

                    {
                       this.props.comments.map((comment) => {
                           return (
                            <Comment commentsShow={this.props.commentsShow} commentObj={comment} key={comment.id} />
                           )   
                       })
                    }
                </div>
            </div>
            )
        }
}


export default Commentspar;

Comment.js Comment.js

import React, {Component} from 'react'; 从'react'导入React,{Component}; import $ from 'jquery'; 从'jquery'导入$;

class Comment extends Component { 类Comment扩展了Component {

 constructor(props) {
    super(props);
    this.state = {
        text:"",
        state:""
    };
  }

componentWillMount () {
    this.setState({
        text:this.props.commentObj.text
    })

}

render () {
    return (
        <div className={"comment-outer " + this.props.commentObj.type} data-type={this.props.commentObj.type}>
            <div className={"comment-inner " + this.state.loaded}>
                <div className={"comment-type " + this.props.commentObj.type}></div>
                <div className="comment-text">
                    <p className="placeholderText">{this.state.text}</p>
                </div>    
            </div>
        </div>
        )
    }
}

export default Comment;

Where have I gone wrong with my structure such that it's giving me this error message when I try and this.commentsShow() a second time and how can I re-arrange my structure to fix this? 我的结构哪里出了问题, this.commentsShow()第二次尝试和this.commentsShow()时都会出现此错误消息,我该如何重新排列结构以解决此问题?

Thanks! 谢谢!

You can't set state of unmounted component. 您无法设置未安装组件的状态。 The commentsShow method is repatedly called even if component has been unmounted and tries to set state of this component and this results in the error. commentsShow方法repatedly调用,即使组件已卸载,并尝试设置此组件的状态,这导致错误。 The same problem will occur if you unmount component before AJAX call finished. 如果在AJAX调用完成之前卸载组件,则会发生相同的问题。 You have to clear your timeout and cancel AJAX clall when component is about to be unmounted to make sure it will not try to set state after unmounting: 您必须清除超时并在要卸载组件时取消AJAX clall,以确保在卸载后它不会尝试设置状态:

class App extends Component {
    ...
    commentsXMLrequest = () => {

        ...
           //the below ajax call goes and retrieves the data to fill my components through state
        this.myXHR =  $.ajax({  
            type: "GET",  
            dataType: "json",  
            crossDomain:true,  
            url:"http://someendpoint.com/endpoint.php",
            success: function(data){

               var parsedComments = JSON.parse(data);  
               var newComments = [/* just above here I construct an array of new objects that look something like {id:0,text:"blah blah",type:"sad"} */];

                    // here I populate the commentsPre array with the new array of objects
                    this.setState({
                        commentsPre:newComments,
                        commentsLoading:""
                    })   

                // here I call the next function (this is the one I would like to repeat)
                this.commentsShow()

            }.bind(this)
        })     
    }
    commentsShow = () => {
        ...
        this.myTimeout = setTimeout(function(){
            // here is where i'm trying to repeat this function every second after incrementing the upToId state but it gives me the error
            this.commentsShow()
        }.bind(this),1000)
    }

    componentWillUnmount() {
        clearInterval(this.myTimeout);
        this.myXHR.abort();
    }
}

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

相关问题 React setState只能更新已安装或安装的组件 - React setState can only update a mounted or mounting component React setstate只能在重新渲染时更新已安装或安装的组件 - React setstate can only update a mounted or mounting component — on rerender React JS setState(…):只能更新已安装或正在安装的组件 - React JS setState(…): Can only update a mounted or mounting component React-setState(…):只能更新已安装或正在安装的组件 - React - setState(…): Can only update a mounted or mounting component 反应警告:setState(…)只能更新已安装或正在安装的组件 - React Warning: setState(…) Can only update a mounted or mounting component 警告:setState(…):只能更新已安装或正在安装的组件 - Warning react : setState(…): Can only update a mounted or mounting component React:setState只能更新已安装或安装的组件 - React: setState can only update a mounted or mounting component 反应警告setState(…):只能更新已安装或正在安装的组件 - React warning setState(…): Can only update a mounted or mounting component setState只能更新已安装或安装的组件 - setState Can only update a mounted or mounting component setState(…):只能更新已安装或正在安装的组件 - setState(…): Can only update a mounted or mounting component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM