componentDidMount 不会在道具更改时触发

时间:2021-05-02 13:36:00

标签: reactjs react-redux

我的 React App 上有一个嵌套组件。

class Home extends React.Component {
  constructor() {
    super();
    this.state = {id : "1"};
  }
  render() {
    return <ShowChart id={this.state.id}/>;
  }
}

我从 Home 渲染组件 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)

我希望 ShowChart 在 Home 组件的值“id”发生变化时触发它的 componentDidMount。但它的行为似乎并非如此。我尝试了 getDerivedStateFromProps()、componentDidUpdate() 方法但没有成功。 欢迎任何解决方案或建议。

4 个答案:

答案 0 :(得分:1)

看看这个答案:React lifecycle hooks not working on redux state update

另外,为什么不在构造函数中调用 API?因为它们已经在那里可用。

答案 1 :(得分:1)

ComponentDidMount() 只会在组件挂载到 dom 时触发一次,在 componentDidMount() 之后调用 ComponentDidUpdate 并且可以在状态/道具更改时执行某些操作。

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}/>;
  }
}

给组件添加key会强制它在id值改变时重新渲染

答案 2 :(得分:0)

显然,我没有正确使用生命周期方法。

Dungeon

这解决了问题。谢谢大家。

答案 3 :(得分:0)

componentDidMount 仅在重新渲染后运行。组件仅通过 state 更改而不是 prop 更改重新渲染。 如果您想更改道具更改状态,请使用 componentDidUpdategetDerivedStateFromProps