道具传递的方法的setState上的无限循环

时间:2018-08-01 16:09:19

标签: javascript reactjs

我无法通过prop从多个嵌套子组件传递到Parent组件的状态设置状态,这导致应用程序由于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}
         )

      }
    }

0 个答案:

没有答案