【发布时间】:2019-09-08 23:38:29
【问题描述】:
我正在使用带有 react native 的 react redux,我有一个平面照片列表。当我单击“赞”按钮时,我只想更新平面列表中的一张照片。以下代码似乎有效,并且照片的状态已更新,但不知何故我的提要在更新后搞砸了。更新前this.props.feed[index]是单个对象,更新后this.props.feed[index]变成对象数组,我做错了什么?我的想法来自:https://stackoverflow.com/a/47651395/10906478
但是,循环遍历 flatlist 的所有项目以找到与传入的 photoId 匹配的项目似乎也非常低效。有没有更好的办法?
屏幕:
toggleLike = async(photoId, index) => {
console.log("before: ", this.props.feed[index]);
await this.props.toggleLike(photoId);
console.log("after: ", this.props.feed[index]);
}
...
<FlatList
data = {this.props.feed}
keyExtractor = {(_, index) => index.toString()}
renderItem = {({item, index}) => (
<View key={index}>
<TouchableOpacity onPress={()=> this.toggleLike(item.photoId, index)}>
<Text>Button</Text>
</TouchableOpacity>
</View>
)}
/>
动作
export const toggleLike = (photoId) => async(dispatch) => {
dispatch({type: "UPDATE_ITEM", photoId: photoId})
}
减速器
export default (state = initialState, action) => {
switch(action.type) {
case "UPDATE_ITEM":
return {...state, feed: [state.feed.map((item,_) => {
if (item.photoId === action.photoId) {
return { ...item, liked: !item.liked };
}
return { ...item };
})]};
// other cases
【问题讨论】:
标签: reactjs react-native redux react-redux react-native-flatlist