Reputation: 838
I am working on a react-native application where I am using react-native-draggable-flatlist for one of the list and unfortunately I have to use shouldComponentUpdate in the component for data manipulation from other list item on another component, but after adding the shouldComponentUpdate, my drag/drop is not not working, I can able to drag and drop but it immediately resets the whole list to original positioning set.
Please help me with some suggestions to make the drag/drop work along with shouldComponentUpdate as I don't want to break the existing functionality
Code
<DraggableFlatList
scrollPercent={5}
data={testData}
renderItem={this.renderItem}
keyExtractor={item => `item-${testkey}`}
onMoveEnd={({ data }) => {
this.setState({ data });
}}
/>
public shouldComponentUpdate(nextProps, nextState) {
if (nextProps.data.length !== nextState.data.length) {
this.setState({
data: nextProps.data
})
}
return true
}
Upvotes: 3
Views: 2183
Reputation: 2452
You shouldn't be using shouldComponentUpdate
for this purpose. If you're just copying props.data
into state.data
, why not just use props.data
directly?
If it's absolutely necessary that you do the copying on every update, then consider using another lifecycle method, like componentDidUpdate
or getDerivedStateFromProps
. You could also use componentWillReceiveProps
, but it has been deprecated and should be avoided.
Upvotes: 1
Reputation: 2937
shouldComponentUpdate
is not intended for doing sideEffects.It is used to reducer render count for prop changes for performance benefit.
shouldComponentUpdate should return true or false determining whether component should rerender.
You may use componentDidUpdate
which fires after prop changes reflect or componentWillReceiveProps
which fires before prop reflects
I recommend using componentDidUpdate
like
componentDidUpdate = (prevProps, prevState) => {
if (this.props.data.length !== this.state.data.length) {
this.setState({
data: nextProps.data
})
}
}
Upvotes: 1