【问题标题】:Why doesn't go my props to child component when I changed my props in Main Component?当我在主组件中更改道具时,为什么我的道具没有转到子组件?
【发布时间】:2021-11-10 16:25:29
【问题描述】:

当我更改状态时,我可以在主组件中读取 newData,但我的更新状态不会进入我的 ChildComponent。我在 ChildComponent 中只读取了 initialData。为什么我的新道具不去 ChildComponent?或者为什么不重新渲染我的 ChildComponent ?

class Main extends Component{
 constructor(props) {
        super(props);
        this.state = {
          data: "initalData",
        }
}

componentDidMount(){
this.changeState();
}

changeState(){
this.setState({data: "newData"})
}

render(){
console.log("my data in Main :",this.state.data)
return(
<ChildComponent dataProps={this.state.data}>
)
}

class ChildComponent extends Component{
constructor(props) {
        super(props);
        const getData = props.dataProps;
        console.log("getData is ",getData)
        this.state = {
          ...,
        }
}
}

【问题讨论】:

    标签: reactjs react-props react-component


    【解决方案1】:

    这是因为类组件的constructor只在初始化时运行一次,而不是每次渲染。

    要始终获取最新值,您需要将它们放在构造函数下方的类组件主体中。

    类似这样的:

    class ChildComponent extends Component{
      constructor(props) {
              super(props);
              this.state = {
                ...
              }
      }
    
      const getData = this.props.dataProps;
      console.log("getData is ", getData)
    
      render() (
        ...
      )
    }
    

    【讨论】:

      【解决方案2】:

      每次传递给它的道具发生变化时,您都可以使用以下内容进行更新

      componentDidUpdate(prevProps, prevState, snapshot){
          if(prevProps !== this.props){
          this
        }
      }
      

      ComponentDidUpdate docs

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-29
        • 1970-01-01
        • 2016-12-17
        • 1970-01-01
        • 2020-02-07
        • 2019-02-08
        • 2019-04-26
        相关资源
        最近更新 更多