如何覆盖状态Redux



我不太明白react-redux中的一些东西。我已经创建了一个名为Introduction的切片,如下所示:

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,它调用调度并在我在介绍片中创建的reducer上使用更新,然后我发送键和值,见下文。

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

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

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

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

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

以object作为有效负载调度动作

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

,你的减速机函数将是这样的

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

这里基于负载,state将被更新,这里fullName和subtitle值将被更新。

最新更新