我刚刚开始在我的项目中使用 Redux-toolkit。标题中提到了我遇到的一件事。
切片组件
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
return 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
商店组件
import { configureStore } from '@reduxjs/toolkit'
import FollowingsReducer from '../reducers/FollowingsSlice'
export default configureStore({
reducer:{
following: FollowingsReducer
}
})
本质上有两个按钮,一个是将项目添加到followings_list,另一个是将项目从中删除。但是,如果我删除一个“项目”,即使在 followings_list 中存在项目之前,我的 followings_list 状态也会变得未定义,或者至少会从以下 reducer 中消失?
import {useDispatch } from 'react-redux';
import{
removeFollowing,
} from "../reducers/FollowingsSlice";
const dispatch = useDispatch()
// this line is called when the button is clicked, I omit other codes
dispatch(removeFollowing({something}))
在调用删除操作之前:
最佳答案
嗨~
你已经解决了吗?
我检查了你的代码。
在您的切片组件代码中
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
return 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
上面切片组件代码中对应的部分
removeFollowing(state, action){
const id = action.payload.user.id_str
return state.followings_list.filter(following =>
following.id_str!==id)
}
您不应立即“返回”过滤器值,而应将过滤后的结果值分配给状态。 您可以通过更改如下代码来做到这一点
removeFollowing(state, action){
const id = action.payload.user.id_str;
let filtered = state.followings_list.filter(following =>
following.id_str!==id);
state.followings_list = filtered;
}
希望这对您有帮助!
关于javascript - 对空状态数组执行过滤器后,Redux-toolkit 状态变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73299440/