reactjs 我如何通过ID找到特定的配置文件

hxzsmxv2  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(168)

我有一个切片机

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;

我的reducer setCurrentProfile不工作。他给了我空数组---x1c 0d1x
下面是我使用配置文件ID的调度,这是配置文件项的组件,在父组件上,我从-- profiles:[]Map它们。逻辑是-首先添加配置文件,然后单击配置文件,我希望将此配置文件设置为当前配置文件:[],

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>
  )
}
py49o6xq

py49o6xq1#

我找到了一个解决办法。不知何故,通过“id”查找不起作用,但如果我使用“name”istead就起作用了。

相关问题