【问题标题】:In React is there a way to remount a component with a button click from another component?在 React 中,有没有办法通过单击另一个组件的按钮来重新安装组件?
【发布时间】:2019-08-17 23:58:37
【问题描述】:

单击按钮后,我将道具从父组件传递给子组件。然后子组件应该根据父组件传递的道具进行 API 调用,但子组件只渲染一次(在安装时)。我做错了什么?

【问题讨论】:

  • 请添加一些代码,以便我们全面了解您的问题????
  • minimal reproducible example 确实有用,但我不认为,在这种情况下,非常需要它! React 用户可以理解 OP 在说什么。
  • 有什么原因你不能在父母中进行调用,然后将结果作为道具传递给孩子?

标签: reactjs


【解决方案1】:

您可以添加 componentDidUpdate 生命周期钩子并检查道具是否已更改并以这种方式创建另一个 API 调用,或者您可以在父组件的子组件上设置新的 key 道具以卸载前一个一个并安装一个新的。

示例

class App extends React.Component {
  state = {
    childKey: Math.random()
  };

  onClick = () => {
    this.setState({ childKey: Math.random() });
  };

  render() {
    const { childKey } = this.state;

    return (
      <div>
        <button onClick={this.onClick}>Remount Child</button>
        <Child key={childKey} prop={childKey} />
      </div>
    );
  }
}

class Child extends React.Component {
  state = {
    isLoading: true,
    data: null
  };

  componentDidMount() {
    setTimeout(() => {
      this.setState({ data: this.props.prop, isLoading: false });
    }, 1000);
  }

  render() {
    const { isLoading, data } = this.state;

    if (isLoading) {
      return <div>Loading...</div>;
    }
    return <div>{data}</div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2015-10-16
    • 2018-01-08
    • 2018-12-26
    • 2021-09-16
    相关资源
    最近更新 更多