React setState:回调子组件的函数

React setState: Callback to function of child-component

setState带回调函数时,如何在父组件中调用子组件的函数?

背景资料

一个简单的测验应用程序的三个组成部分:

App.jsx  
-- Questions.jsx  
-- Results.jsx 

要访问结果组件和问题组件中的答案,答案必须保存在应用程序组件的状态中。

要修改应用程序组件的状态,每次用户回答问题时,我都需要调用一个从应用程序组件向下传递到问题组件的函数。设置应用程序组件的状态后,应显示下一个问题。因此,应该调用问题组件中的函数 nextQuestion()。通常,我会写 setState({results: results}, nextQuestion()) 但由于 nextQuestion() 是问题组件的函数而不是应用程序组件的函数,所以这不起作用。

我该如何解决这个问题?

非常感谢!

在问题部分:

checkAnswer = (answer) => {

    if (answer !== this.state.solution) {

      let s = this.state;
      this.props.saveResult(s.question, s.solution[0], answer);

      //[...]
    }
  };

newQuestion = () => {
    //[...]

    let question = [...this.state.question];
    let solution = [...this.state.solution];

    const task = taskGenerator.taskDirectory[taskId](); //generate new question + solution
    question = task.question;
    solution = task.solution;
    this.setState({ question, solution });
  };

在应用组件中:

saveResult = (question, solution, answer) => {
    let results = cloneDeep(this.state.results)
    results.question = question
    results.solution = solution
    results.answer = answer
    this.setState({ results: results }, newQuestion()); //here is the problem; how do I call the newQuestion function of the child component?
  };
class App extends Component {
...
  setAnswers(answers, callback){
     this.setState({results:answers},callback)
  }
  render(){
    return <Questions setAnswers={this.setAnswers}/>
  }
}

class Questions extends Component {

  onSubmit(answers){
     this.props.setAnswers(answers,this.nextQuestion)
  }
}

另一种方法是对 Questions 子组件中的状态变化做出反应,这可能是更好的方法。

如果我对你的问题理解正确,你应该能够将函数作为 props 从父组件传递给子组件。我相信这个 post 也能回答您的问题。

干杯!

how do I call a function of a child component in the parent component when using setState with a callback function?

简而言之,您不需要 :) 相反,您将状态 从父级传递给子级 。这实际上是您问题的根源:

but since nextQuestion() is a function of the questions component and not of the app component, this does not work.

简而言之,作为 React 开发人员,有两个“规则”可以遵循您的应用程序中状态需要进入的位置。要理解它们,您必须将您的应用程序视为一棵“树”,App 在顶部,所有子组件、孙组件等在下面...

  1. 状态必须在每个需要使用状态的组件以上
  2. 应用树中的状态应尽可能低(同时仍遵循#1)

您似乎在尝试遵循规则 #2 并保持低状态(良好)...但您的应用违反了第一条规则:您有状态(nextQuestion 依赖于 this.state.question) 您的 App 所依赖的。该状态(在您的应用程序树中)比需要的状态“低”,并且由于它不在 App 级别,App 无法使用它。

这意味着您需要将 nextQuestion(以及为其供电的州)移至 App,以便您的代码在 App 可以 访问 nextQuestion。然后,您可以将 Question 需要的任何数据作为 propsApp.

传递

使用此结构,您的状态(以及相关函数,如 nextQuestion)将活到它需要活到的高度(即在 App 级别),因此所有依赖的逻辑它具有访问权限,并且任何“较低”组件(如 Question)将简单地通过 props.

将该状态“向下传递到树”