繁体   English   中英

React - 当父 state 更改时更新子级,而不使用 componentWillReceiveProps()?

[英]React - update child when parent state changes, without using componentWillReceiveProps()?

我正在 React 中构建 JSON 编辑器,而我使用的库没有componentWillReceiveProps挂钩。 我对 React 有点陌生,并试图在父 state 更改时立即更新<Editor />组件。

import React, { Component } from "react";
import { JsonEditor as Editor } from "jsoneditor-react";

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      originalData: [],
      newData: []
    };
    this.handleChange = this.handleChange.bind(this);
    this.resetForm = this.resetForm.bind(this);
  }

  componentDidMount() {
    this.setState({
      data: ["original data"],
      originalData: ["original data"],
    });
  }

  handleChange(val) {
    this.setState({
      newData: val
    });
  }

  resetForm() {
    this.setState({
      data: this.state.originalData // this *does* update the state but the <Editor /> component doesn't reflect it.
    });
  }

  render() {
    const { data } = this.state;
    return (
      <div className="Home">
        <main>
          <button onClick={this.resetForm}>
            Reset
          </button>
          <Editor // no componentWillReiveProps available
            value={data}
            onChange={this.handleChange}
          />
        </main>
      </div>
    );
  }
}

如果子组件中没有任何 state 更新程序,则可以使用key

它完全卸载和安装组件。

<Editor
   key={this.state.data}
   value={this.state.data}
   onChange={this.handleChange}
/>

这可能使它起作用:

this.setState({
      data: [...this.state.originalData] 
});

暂无
暂无

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

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