我有一个父组件将状态作为 Prop 传递给子组件。在页面加载时,使用父组件中的 componentDidMount
调用 API,并且传递给子组件的数据的初始状态会发生变化。更改会反射(reflect)在父组件中,但不会反射(reflect)在子组件中。
这是我的代码的摘录:
loan.js(父级)
<ForecloseBtn id={this.state.lead_id} foreclose={this.state.isForeclosed }/>
ForecloseBtn.js(子级)
import React from 'react';
import { render } from 'react-dom';
class ForecloseBtn extends React.Component {
constructor(props) {
super(props);
console.log(this.props);
this.state = {
lead_id: this.props.id,
isForeclosed: this.props.foreclose,
};
}
render() {
return (
......
)
}
};
export default ForecloseBtn;
所以在这里,状态 lead_id
和 isForeheld
在父组件中发生变化,但在子组件中没有变化。如何在子组件中也进行状态更新?
最佳答案
这就是为什么在你的子组件中你只需要在构造函数中准备好 props 并相应地设置它的状态;如果它们稍后发生变化,您不会更新子组件状态,因此不会进行重新渲染。
有几个选项可以解决这个问题,最简单的就是不在子组件中使用 state,而是直接使用 props
;在这种情况下,一旦父组件更新,新的 props 将触发子组件的重新渲染。这也是最干净的解决方案,您只有一个事实来源,即从父组件传递到子组件的 props。
或者,您可以在子级中使用 componentDidUpdate
并根据从父级收到的新 props 更新其状态:
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.id !== prevProps.id) {
this.setState({ lead_id: this.props.id });
}
if (this.props.foreclose !== prevProps.foreclose) {
this.setState({ isForeclosed: this.props.foreclose });
}
}
关于javascript - 子组件reactjs的动态props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55746642/