簡體   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