React redux 更新 flatlist item 但将 item 变成 Array

React redux updates flatlist item but turns item into an Array

我正在使用 react redux 和 react native,我有一张平面照片列表。当我点击赞按钮时,我只想更新平面列表中的一张照片。以下代码似乎有效,并且照片的状态已更新,但更新后不知何故我的提要搞砸了。更新前,this.props.feed[index] 是单个对象,更新后,this.props.feed[index] 变成对象数组,我做错了什么?我的想法来自:

但是循环遍历 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

您在数组内调用 map,returns 嵌套数组:

return {...state, feed: /* Here ->*/[state.feed.map((item,_) => {
    if (item.photoId === action.photoId) {
        return { ...item, liked: !item.liked };
    }
    return { ...item };
})]};

应该这样做:

return {
  ...state, // Current state
  feed: state.feed.map((item, _) => { // map returns a new array
    if (item.photoId === action.photoId) {
      item.liked = !item.liked;
    }
    return item;
  })
}

对于数组形式的提要,请仔细查看您的代码。您会看到您已将 feed 的值包装在方括号中,并在数组中 运行 映射。所以feed是一个数组,map也是一个数组。这就是为什么在 state.feed 的每个索引点都有一个对象数组。我通常建议您去掉周围的方括号,让您的地图创建数组。

然而,这实际上并不是问题的根本原因,还有更彻底的解决方案。

如果需要在不打乱数组顺序的情况下找到匹配的 ID 并更新 "liked" 值,请尝试在数组上使用 findIndex 而不是映射。找到您的项目所在的索引并更新该值。如果它抱怨直接改变 Redux 存储值,您可能需要克隆数组和内部对象。

祝你好运!