Reputation: 6005
I'm getting a list of items
as a prop
through the redux store. This prop is asyncronous.
My ListView works with syncronous hardcoded data. So the problem is populating with the prop when I actually receive it.
I'm making a ListView out of this item prop data. What's the best practice on life cycle choices to setState with this prop? I've tried componentDidMount
- but that's too early and only called once. I tried componentWillReceiveProps
- I get the prop, but my view doesn't change. I also tried componentWillUpdate
and I get too many calls! I'm tempted to put it in the render function because I know I can grab that prop when I get it but that makes the render function no longer pure.
Thanks for any help!
this.setState({
dataSource: this.state.dataSource.cloneWithRows(this.props.items);
})
Upvotes: 1
Views: 862
Reputation: 6005
The solution was that I actually needed to convert items as a List
from immutable to a JS Array
for the ListView. Not what I originally thought the problem was in the question.
Here's the solution:
componentWillReceiveProps(newProps){
if(newProps.items){
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newProps.items.toJS())
})
}
}
I'm still wondering if I'm using best practice by using componentWillReceiveProps
. I'm also wondering if it's a little strange that I have to convert from a List to an Array, but if it's purely presentational that is ok, right?
Upvotes: 3
Reputation: 8936
When using componentsWillReceiveProps
, it's good practice to check whether those props have changed. Also not sure why you have to do .toJS()
, you just need to return a new array so React knows to update.
componentWillReceiveProps(newProps){
if (newProps.reasonOptions !== this.props.reasonOptions){
this.setState({
dataSource: this.state.dataSource.cloneWithRows([...newProps.items])
});
}
}
Upvotes: 0