0

I try to do infinite scroll by detecting the items are different in componentWillReceiveprops, like so

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>)
}

But items in my render method and the items in componentWillReceiveprops is not the same? I also tried forceUpdate still coulnd't make this infinite scroll work.

Celdric Kang
  • 389
  • 2
  • 4
  • 12

1 Answers1

2

props are supposed to be immutable. See this answer by Mike Driver. Quoting:

The React philosophy is that props should be immutable and top-down. This means that a parent can send whatever prop values it likes to a child, but the child cannot modify its own props. What you do is react to the incoming props and then, if you want to, modify your child's state based on incoming props.

So you don't ever update your own props, or a parent's props. Ever. You only ever update your own state, and react to prop values you are given by parent.

You are using this.props.items.push(...) which is altering the props being received. This is something React advises you not to do, and it's bound to cause all sorts of trouble. You will need to start thinking differently about how you change application state in your app.

As a suggestion, you can make the parent component send down a method as a prop to your child component which will be called back whenever you need to change the component's state.

Community
  • 1
  • 1
glhrmv
  • 1,712
  • 1
  • 16
  • 23
  • => use `this.setState()` – Aprillion Jul 08 '17 at 17:40
  • 1
    He is pushing directly onto the `props` which makes me think he might want to use them in the parent component, so I suggested passing in a callback method from the parent. If he's keeping that `items` array solely in the child component then yeah, `setState` is the way to go. – glhrmv Jul 08 '17 at 17:43