如何通过ID查找指定Profile?Redux Toolkit reducer失效问题
问题描述
使用Redux Toolkit创建的userSlice中,setCurrentProfile reducer无法正常工作,调用后currentProfile返回空数组。业务逻辑为:点击Profile项组件时,通过dispatch传入Profile的ID,将对应的Profile设置为currentProfile。
现有userSlice代码
import { createSlice } from '@reduxjs/toolkit'; const initialState = { id:null, email:null, profiles:[], currentProfile:[], } export const userClise = createSlice({ name: 'user', initialState, reducers: { setUser: (state,action) => { state.id = action.payload.id; state.email = action.payload.email; state.profiles = action.payload.profiles; }, removeUser: (state) => { state.id = null; state.email = null; state.profiles = null; }, addProfile: (state,action) => { // SLICE TO ADD PROFILE TO profiles.Array state.profiles.push(action.payload) }, setCurrentProfile: (state,action) => { // SLICE TO FIND AND SET PROFILE state.currentProfile.push(state.profiles.filter((profile) => profile.id === action.payload)); } }, }) export const { setUser, removeUser, addProfileName, setCurrentProfile } = userClise.actions; export default userClise.reducer;
Profile项组件代码
import React from 'react' import { Link } from 'react-router-dom'; import { useDispatch } from 'react-redux'; import { setCurrentProfile } from '../../../redux/userSlice'; export default function UserProfileItem({name,bgImg,redirect,id}) { const dispatch = useDispatch(); const handleSetProfile = () =>{ dispatch(setCurrentProfile(id)) } return ( <Link to={`/${redirect}`}> <li onClick={handleSetProfile} className='w-[153px] h-[201px] sm:w-[140px] sm:h-[175px] cursor-pointer mr-7 group flex items-center flex-col'> <div className='rounded-md border-4 border-transparent bg-center bg-cover w-full h-full group-hover:buttonUserScreen' style={{ backgroundImage:`url(${bgImg ? bgImg : "https://upload.wikimedia.org/wikipedia/commons/0/0b/Netflix-avatar.png"})`}}> </div> <span className='mt-3 group-hover:text-[#fff]'>{name || "user name"}</span> </li> </Link> ) }
问题原因
filter方法误用:filter返回的是数组,哪怕仅匹配一个元素,用push将其加入currentProfile会导致二维数组(如[[匹配的profile]]);无匹配项时则变成[[]],表面呈现为空数组。removeUser赋值错误:将profiles设为null,后续调用addProfile会触发null.push()报错,导致profiles无法正常添加数据,setCurrentProfile自然找不到对应项。- action导出笔误:导出的
addProfileName应为addProfile,会导致调用添加Profile的action时找不到方法。 currentProfile初始类型不合理:业务需求是单个当前Profile,初始值设为数组[]不符合预期,应设为null。
解决方案
修改后的userSlice代码如下:
import { createSlice } from '@reduxjs/toolkit'; const initialState = { id: null, email: null, profiles: [], currentProfile: null, // 改为null,匹配单个对象的业务需求 } export const userSlice = createSlice({ // 修正拼写错误userClise -> userSlice name: 'user', initialState, reducers: { setUser: (state, action) => { state.id = action.payload.id; state.email = action.payload.email; state.profiles = action.payload.profiles; }, removeUser: (state) => { state.id = null; state.email = null; state.profiles = []; // 重置为空数组而非null,避免后续push报错 }, addProfile: (state, action) => { state.profiles.push(action.payload); }, setCurrentProfile: (state, action) => { // 使用find方法获取单个匹配的profile对象,直接赋值给currentProfile state.currentProfile = state.profiles.find((profile) => profile.id === action.payload); } }, }) // 修正笔误:addProfileName -> addProfile,修正拼写userClise -> userSlice export const { setUser, removeUser, addProfile, setCurrentProfile } = userSlice.actions; export default userSlice.reducer;
额外注意事项
- 添加Profile时,确保传入的
payload包含正确的id字段,否则find方法无法匹配到对应项。 - 若需兼容无匹配项的场景,可在
setCurrentProfile中处理null情况,比如设置默认值或提示用户。
内容的提问来源于stack exchange,提问作者AleshaLearner
相关产品推荐
相关产品推荐

