简体   繁体   English

家长重新提交不会更新子道具

[英]Parent rerender doesn't update child props

I have a parent component and a child component. 我有一个父组件和一个子组件。 In the parent component I defined the state which is passed as props to my child component. 在父组件中,我定义了作为道具传递给我的子组件的状态。 I'm also passing the function "onUpdateQuestion" in the props of the child component. 我还在子组件的道具中传递了函数“ onUpdateQuestion”。 This function will be executed every time the value of the input field of the child changes (so a re-render will occur). 每当子项的输入字段的值更改(因此将发生重新渲染)时,将执行此功能。

export default class Parent extends React.PureComponent<{},{question:Question}> {
  public state = {
    question: new Question()
  };

  public onUpdateQuestion = (): void => {
    let _question = this.state.question; 
    this.setState({ question: _question });
  };

  public render(): React.ReactNode {
    return (
      <QuestionEditorChild
      question={this.state.question}
      onUpdateQuestion={this.onUpdateQuestion}/>);
  }
}

class QuestionEditorChild extends React.Component<{question: Question; onUpdateQuestion: Function;}> {
  render() {
    console.log(this.props.question.description);

    return (
      <div>
        <h2>Question</h2>
        <input
          value={this.props.question.description}
          onChange={e => {
            this.props.question.setDescription(e.target.value);
            this.props.onUpdateQuestion();
          }}
        />
      </div>
    );
  }
}

class Question implements IQuestion {
  public description: string;

  constructor(question?: IQuestion) {}

  public setDescription(value: string): void {
    this.description = value;
  }
}

interface IQuestion {
  description: string;
}

My child component never gets re-rendered again. 我的子组件再也不会重新渲染。 Does this have something to do with the function setDescription() I'm executing in the child component? 这与我在子组件中执行的setDescription()函数有关吗?

What are the best practices for re-rendering the child correctly while working with models/interfaces? 在使用模型/界面时正确重新渲染孩子的最佳实践是什么?

public onUpdateQuestion = (): void => {
    let _question = this.state.question; 
    this.setState({ question: _question });
};

The code above isn't actually using any new data from your form. 上面的代码实际上并没有使用表单中的任何新数据。

It should be... 它应该是...

onUpdateQuestion = (incomingData) => {
    this.setState({ question: incomingData })
}

So technically your code, never updating, is correct because it's always using new Question() which is created once, then never changes. 因此从技术上讲,您的代码(永远不会更新)是正确的,因为它始终使用新的Question() ,它只创建一次,然后再更改。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM