我的react App上有一个嵌套组件。
class Home extends React.Component {
constructor() {
super();
this.state = {id : "1"};
}
render() {
return <ShowChart id={this.state.id}/>;
}
}我从主页渲染组件ShowChart,并将this.state.id作为一个道具传递。ShowChart是一个带有redux connect()的组件。
class ShowChart extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
componentDidMount(){
//API_Call(this.props.id)
//This API call uses props.id as parameter and redux store provides the API response
}
render() {
return (<div>{API_response}</div>);
}
}
function mapStateToProps(state) {
return {
//
};
}
function mapDispatchToProps(dispatch) {
return {
//
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ShowChart)我希望每当Home组件的值'id‘发生变化时,ShowChart就会触发它的componentDidMount。但它似乎并不是这样的。我尝试了getDerivedStateFromProps()和componentDidUpdate()方法,但都没有成功。欢迎任何解决方案或建议。
发布于 2021-05-02 22:01:16
显然,我没有正确使用生命周期方法。
componentDidUpdate(prevProps) {
if (this.props.id !== prevProps.id) {
//API_Call(this.props.id)
}
}这就解决了问题。感谢大家。
发布于 2021-05-02 21:46:03
看看这个答案:React lifecycle hooks not working on redux state update
另外,为什么不在构造函数中调用API呢?因为它们已经在那里可用了。
发布于 2021-05-02 21:58:05
ComponentDidMount()只会在组件挂载到dom时触发一次,ComponentDidUpdate是在componentDidMount()之后调用的,并且在状态/属性发生变化时可以用于执行某些操作。
componentDidUpdate(prevProps, prevState) {
//api call
//state update
}我认为您想要做的是在id更改时重新呈现ShowCart,如果是这样的话,您可以这样做
class Home extends React.Component {
constructor() {
super();
this.state = {id : "1"};
}
render() {
return <ShowChart id={this.state.id} key={this.state.id}/>;
}
}向组件添加密钥将强制它在id值更改时重新渲染。
https://stackoverflow.com/questions/67356996
复制相似问题