I added the ability to 'like' a post. And suddenly react-native is crawling at a snails pace. Im new to react so aren't really sure where and when to properly set state.
How should I properly attach the ability to like a row, in a listView table??
Heres the code...
The 'like' text to click on is this....
<Text onPress={this.likePost.bind(this, feeditem.post_id)}>{feeditem.likes} likes</Text>
Then the 'liking' function is this...
likePost(id){
if(this.state.feedData!=null){
var d = this.state.feedData;
// Find row by post_id
var ix = d.findIndex(x => x.post_id===id);
// Only set state if user hasn't already liked
if(d[ix].you_liked==0){
// Mark as liked, and increment
d[ix].you_liked=true;
d[ix].likes = parseInt(d[ix].likes)++;
// Set the state after liking
this.setState({
feedData: d,
feedList: this.state.feedList.cloneWithRows(d)
});
}
}
}
It works, and it properly updates the data, and shows in the dev tools just fine. However, the rendering of the new state visually is taking over a minute.
Am I updating the state wrong? What is the cost for setState? I thought react was supposed to just re-render the changes it sees in the virtual DOM. Why then does it seem like its rerendering my entire listView. And why over 1 minute load time?? (obvious memory leak somewhere)??
Also, is it possible to just increment the integer on the 'DOM' without triggering re-renders?
Render your ListView
passing dataSource
and renderRow
props
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow}/>
);
}
Create renderRow
function, where your can access your data and index of clicked row
_renderRow = (rowData, sectionIndex, rowIndex, highlightRow) => {
return (
<TouchableOpacity onPress={() => {
//Here you shoud update state
}}/>
);
};
Furthermore, you always need to make copy of a state before manipulating it, because its immutable object. Try working with state mutating libraries, use https://facebook.github.io/react/docs/update.html or other options.
Animations can take a long time because of the chrome debugger. A small way to mitigate this is using InteractionManager
likePost(id){
InteractionManager.runAfterInteractions(() => {
if(this.state.feedData!=null){
var d = this.state.feedData;
// Find row by post_id
var ix = d.findIndex(x => x.post_id===id);
// Only set state if user hasn't already liked
if(d[ix].you_liked==0){
// Mark as liked, and increment
d[ix].you_liked=true;
d[ix].likes = parseInt(d[ix].likes)++;
// Set the state after liking
this.setState({
feedData: d,
feedList: this.state.feedList.cloneWithRows(d)
});
}
}
});
}
Or disable chrome debugging and use android monitor to see debugging messages.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.