我的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)
}
}这就解决了问题。感谢大家。
https://stackoverflow.com/questions/67356996
复制相似问题