componentRecieveProps获取与渲染

时间:2017-07-08 16:48:03

标签: javascript reactjs ecmascript-6

我尝试通过检测componentWillReceiveprops中的项目不同来进行无限滚动,就像这样

componentWillReceiveprops(nextProps) {

        //if infinite load triggered
        if(!isEqual(nextProps.items, this.props.items)){
            this.props.items.push(...nextProps.items)
            //this.forceUpdate()
            console.log(this.props.items) // newly items are merge with previous items array, worked. 
        }

}

render() {
    const { items } = this.props

    console.log(items) // still old items, newly loaded items is not here?

    return(<div></div>)
}

但我的渲染方法中的itemsitems中的componentWillReceiveprops不一样吗?我也试过forceUpdate仍然无法使这个无限滚动工作。

1 个答案:

答案 0 :(得分:2)

props应该是不可变的。见this answer by Mike Driver。引用:

  

React的理念是道具应该是不可变的和自上而下的。这意味着父母可以将其喜欢的任何道具值发送给孩子,但孩子不能修改自己的道具。你做的是对传入的道具作出反应然后,如果你愿意,根据传入的道具修改你孩子的状态。

     

因此,您无法更新自己的道具或父母的道具。永远。您只需更新自己的状态,并对父母给出的道具值做出反应。

您正在使用this.props.items.push(...)来改变收到的道具。这是React建议你不要做的事情,它必然会造成各种各样的麻烦。您将需要开始以不同的方式思考如何在应用程序中更改应用程序状态。

作为建议,您可以让父组件向您的子组件发送一个方法prop,只要您需要更改组件的状态,就会回调该方法。