html - componentWillRecieveProps 会在每次收到 props 时运行吗

标签 html reactjs

我正在阅读 React facebook 的文档和 there据记载

Invoked when a component is receiving new props. This method is not called for the initial render.

但稍后在 this链接,已经解释过即使 props 相同也会调用此方法,因为 props 可以是引用,而这些引用处的数据可能不同。

所以,我的问题是是否每次我们收到新 Prop 时都会调用它。

最佳答案

初始渲染意味着当你的组件第一次加载它所拥有的任何数据时。 例如:

Parent
    constructor() {
            super();
            this.state = {
                viewData:undefined,
            };
    componentDidMount(){
      let myData = yourStore.getData();
      this.setState({viewData:myData})
    }
    updateView(){
     let myData = yourStore.getData();
      this.setState({viewData:myData})
    }


render() 
   {
    return(
      <div>
         {
      this.state.viewData && this.state.viewData.map(function (obj, index) {
        return <childComponenet data={obj} key={index}/>
       })
        }       
      </div>
     <button onClick={this.updateView.bind(this)>Update</button>}
     )
}

子组件:

constructor() {
        super();
        this.state = {
            childData:this.props.data
            }
        };

//componentDidMount(){
  //this.setState({childData:this.props.data}) }

componentWillReceiveProps(newProps){
   this.setState({childData:newProps.data})//this method will not get called first time
}

render(){
   return(
   <span>{this.state.childData}</span>
   )
}

构造函数只初始化一次。所以当第一次渲染子组件时,它会设置 state 变量。现在,当您单击父组件中的更新状态时,state 会更新,它将更新后的 state 作为 props 传递给子组件。在这种情况下,将调用 componentWillReceiveProps 方法并更新子组件状态。

注意:componentWillReceiveProps 不检查 props 的内部值。这意味着即使以前和当前的 Prop 相同,它也会起作用。因此答案是。每次从父级接收到新 Prop 时,它都会被调用。

关于html - componentWillRecieveProps 会在每次收到 props 时运行吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36011875/

相关文章:

reactjs - 使用 typescript 时属性 'theme' 不存在

javascript - 使用 immutable.js 相对于 Object.assign 或扩展运算符的优势

testing - 让 Mocha 与 React Native 一起工作 - 错误 w/requiring & addons

javascript - 如何将函数绑定(bind)到通过 Ajax 加载的元素

javascript - 简单图像幻灯片上的随机动画

javascript - 如何从 javascript MDL 文本字段显示错误密码错误消息

javascript - 无法在 LAN React Native 上运行我的 Expo 应用程序

javascript - 如果值为 0,我可以隐藏文本框值吗?

下拉列表悬停时的 Html 输入表单样式

javascript - 如何在 ReactJS 中跳过某些路由的页眉和页脚?