Redux Toolkit空数组执行filter后state变为undefined问题求助
问题分析与修复
问题根源
你的removeFollowing reducer存在关键错误:直接返回了state.followings_list.filter(...)的结果,这会把整个following slice的状态从对象结构({followings_list: []})替换成数组结构。
当followings_list为空时,filter返回空数组,此时整个following的状态就变成了空数组,而非原本的对象结构。这导致后续访问state.following.followings_list时,因为数组没有followings_list属性,结果为undefined,视觉上就像是reducer结构消失了。
修复后的Slice代码
修改removeFollowing的逻辑,保持state的对象结构,直接更新followings_list属性:
import { createSlice } from '@reduxjs/toolkit' const followingSlice = createSlice({ name: 'followings', initialState:{ followings_list: [] }, reducers:{ addFollowing(state, action) { const user = action.payload.user state.followings_list.push(user) }, removeFollowing(state, action){ const id = action.payload.user.id_str // 正确做法:更新followings_list属性,而非替换整个state state.followings_list = state.followings_list.filter(following => following.id_str !== id) } } }) export const { addFollowing, removeFollowing} = followingSlice.actions export const selectFollowings = (state) => state.following.followings_list export default followingSlice.reducer
额外提示
- Redux Toolkit内置的Immer允许你直接“修改”state,实际上它会帮你生成不可变的新状态,所以直接给
state.followings_list赋值新数组是完全安全的。 - 确保调用
removeFollowing时,action.payload.user确实存在且包含id_str,避免出现Cannot read property 'id_str' of undefined的错误。比如可以在调用前做校验:// 调用移除操作时的校验示例 if (user && user.id_str) { dispatch(removeFollowing({ user })) }
内容的提问来源于stack exchange,提问作者zxcisnoias
相关产品推荐
相关产品推荐

