![](/img/trans.png)
[英]Trigger a function in another component on click a button from a different component in React
[英]In React is there a way to remount a component with a button click from another component?
点击按钮后,我将道具从父母传递给子组件。 然后,子组件应根据父组件传递的props进行API调用,但子组件只渲染一次(安装时)。 我究竟做错了什么?
您可以添加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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.