如何覆盖状态Redux

1sbrub3j  于 2022-11-24  发布在  其他
关注(0)|答案(2)|浏览(134)

我不明白react-redux中的一些东西。我创建了一个叫做Introduction look below的切片:

import { createSlice } from "@reduxjs/toolkit";
import { IntroductionFields } from "../helpers/interface";

const initialState: IntroductionFields = {
  fullName:'',
  subtitle:'',
  description:'',
  location:'',
  email:'',
  portfolio: {name:'' , url:''},
  project: {name: '' , url: ''},
  learning: '',
  collaborating: '',
  else: '',
}

const Introduction = createSlice({
  name: 'intro',
  initialState,
  reducers:{
    update(state, actions){
      const key = actions.payload.name;
      const val = actions.payload.value;
      state.fullName = val; // WORK 
      state = {...state, [key]: val} // NO WORK
      console.log(actions.payload.name , " " , actions.payload.value);
    },

  }
})

export const IntroductionActions = Introduction.actions;
export default Introduction;

我还有两个组件,第一个组件有字段(输入),每个字段都有一个onChange,它调用dispatch,并在我在介绍片段中创建的reducer上使用update,我发送键和值,见下文。

const Intro: React.FC<Props> = ({ moveForward }) => {
  const dispatch = useDispatch();
  const changeHandler = (event: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => {
    const {name , value} = event.target;
    dispatch(IntroductionActions.update({name, value}))
  }

    return (.... // HERE I HAVE INPUTS...)

}

在第二个组件中,我希望从Introduction切片中获取值,因此,如果我更改了Intro组件中的某些字段,我希望在Preview组件中看到这些更改。

import React, { useEffect } from 'react'
import classes from './Preview.module.scss';
import { useSelector } from 'react-redux';
import { RootState } from '../../../store/store';

const Preview = () => {
  const introduction = useSelector((state:RootState) => state.intro);
  
  return (
    <div className={classes.previewContainer}>
      {introduction.fullName && <h1>Hi! My name is {introduction.fullName}</h1>}
    </div>
  )
}

export default Preview

如果您查看第一个代码部分,您将看到这两行代码。

state.fullName = val; // WORK 
  state = {...state, [key]: val} // NO WORK

如果我直接写入状态字段,它工作完美,但如果我尝试做第二行,它不工作...我希望它是动态的,这就是为什么我想使用第二行...

vuv7lop3

vuv7lop31#

将对象作为有效负载调度操作

dispatch(IntroductionActions.update({fullName: name, subtitle: subtitle}))

你的减速器函数是这样的

update(state, actions){
      return ({...state, ...actions.payload})
}

这里基于有效负载,状态将得到更新,这里fullName和subtitle值将得到更新。

hsgswve4

hsgswve42#

您可以像这样设定状态,因为不需要将整个状态复制到新状态。

update(state, actions){
  const key = actions.payload.name;
  const val = actions.payload.value;
  state[key] = val;
},

创建Redux状态切片一节将深入解释如何/为什么

相关问题