reactjs - React 在父级状态更改后更新子级的 props

标签 reactjs react-props

我正在尝试将 Draft.js 的编辑器状态从编辑器组件传递到我自己的 Sidebar 组件。

使用最上面的组件 Notes 我使用回调从 CustomEditor 获取编辑器状态并将其设置为 Notes 状态。然后,我将该状态作为 prop 传递给 Sidebar

问题是 prop 是在回调触发之前设置的。我正在考虑 setTimeout 但这似乎很粗糙。我知道 UNSAFE_componentWillReceiveProps() 但文档不推荐它。对于这个用例有什么 react 吗?

export class Notes extends Component {
  constructor(props) {
    super(props);
    this.getEditorState = this.getEditorState.bind(this)
    this.state = {
      editorState: "the placeholder data Sidebar should not have as a prop"
    };
  }

  getEditorState(state) {
    console.log(state)
    this.setState({editorState: state})
  }

  render() {
    return (
      <section id="Notes">
        <div id="editor-holder">
          <Sidebar currentEditorState={this.state.editorState}/>
          <div id="Editor">
            <FileHeader />
            <CustomEditor getState={this.getEditorState}/>
          </div>
        </div>
      </section>
    );
  }

}

export default Notes;

最佳答案

新的 Context API 就是此类问题的解决方案。我花了一些时间来理解它,但我想出了将 editorState 获取到 Sidebar 作为 Prop 。

  export const NoteContext = React.createContext("placeholderEditorState");

  export class Notes extends Component {
    constructor(props) {
      super(props);
      this.getEditorState = this.getEditorState.bind(this)
      this.getFolderData = this.getFolderData.bind(this)
      this.state = {
        editorState: null,
        folderData: null
      };
    }

    getEditorState(state) {
      this.setState({editorState: state});
    }

    getFolderData(data) {
      this.setState({folderData : data})
    }

    render() {
      return (
        <section id="Notes">
          <TopBar />
          <div id="editor-holder">

            <NoteContext.Provider value={{editorState: this.state.editorState}} >
              <NoteContext.Consumer>
                {(context)=>{ return (
                  <Sidebar currentEditorState={context.editorState} getFolderData={this.getFolderData}/>
                )}}
              </NoteContext.Consumer>
            </NoteContext.Provider>

              <div id="Editor">

                <NoteContext.Provider value={{folderData: this.state.folderData}} >
                  <FileHeader />
                </NoteContext.Provider>

                <CustomEditor getState={this.getEditorState}/>
              </div>

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

现在看来很简单,说明我学到了很多东西!如果我可以改进这里的任何内容,请告诉我。

关于reactjs - React 在父级状态更改后更新子级的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50126085/

相关文章:

javascript - 在 react router v6 中使用导航功能时如何传递数据

javascript - 避免在 React Flux 应用程序中重新呈现受控输入

reactjs - 输入变化重置计时器

javascript - 如何通过 react 将数据从对话框发送回父容器?

javascript - 如何使用map将数据从reactJs上的组件传递到另一个组件?

javascript - this.state 与 React 中的状态

reactjs - 在react+redux中预加载组件数据的正确方法

javascript - 为什么react.js事件委托(delegate)很快?

reactjs - 如何根据状态处理 React-Redux 中的通知?

ReactJS 从我的自定义表中向特定行添加数据