首页 > 解决方案 > 道具传递的方法的 setState 上的无限循环

问题描述

我在从各种嵌套子组件传递给父组件的道具设置状态时遇到问题,这会导致应用程序由于 this.setState() 的无限循环而崩溃

这是最里面的子组件

SingleChoice.jsx

class SingleChoice extends Component {
        state = {
        choices: [{ name: "" }],
        questionName: "",
        type: "singleChoice"
      };

      componentDidUpdate() {
        this.props.updateState(this.state);
      }

 }  

由 AddQuestionOptions 调用

AddQuestionOptions.jsx

class AddQuestionOptions extends Component {

  updateState = state => {
    this.props.updateState(state);
  };
  render(){
    <SingleChoice updateState={this.updateState} />
  }
}

然后由 QuestionOptions 调用

QuestionOptions.jsx

    class QuestionOptions extends Component {
     state = {
      value: 0,
      questions: [{ name: "" }]
     };
     {...}
     updateState = state => {
        this.props.updateQuestion(state);
      };
     render(){
       return(
           <AddQuestionOptions
            updateState={this.updateState}
          />
       )
     }
   }

然后在父组件中调用方法...

SurveyForm.jsx
    class SurveyForm extends Component {
       state={
       ...,
       questions: []
       }
       updateQuestion = state => {
         const newQuestions = this.state.questions.map((question, idx) => {
           if (idx !== this.state.questions.length - 1) return question;
           return { ...question, state };
         });
         this.setState({
           questions: newQuestions
         });
      };
      render(){
         return(
             <QuestionOptions
               updateQuestion={this.updateQuestion}
         )

      }
    }

标签: javascriptreactjs

解决方案


推荐阅读