如何在Redux中存储具有数组作为值的对象数组?



如何在Redux中存储具有数组作为值的对象数组,其中值是项目数组,键是像名称一样的字符串。我必须存储如下内容:

[{
name: 'ron',
team: ['josh','brian'],
},
{
name: 'marie',
team: ['ann', 'kevin']
}
]

这是我只有名字的代码:

import {v4 as uuid} from 'uuid';
const initalState = [
{
id: uuid(),
name: ''
}
];

const trainerReducer = (state = initalState, action) => {
const {type, payload} = action;
switch (type) {
case 'CREATE_TRAINER':
console.log('payload', payload);
return [...state, {id: uuid(), name: payload.name}];

default:
return state;
}
};
export default trainerReducer;

此外,任何关于如何在redux中添加,更新,删除此文件的文档将不胜感激。

当你创建一个训练师时,你就通过了这个团队。

const trainerReducer = (state = initalState, action) => {
const { type, payload } = action;
switch (type) {
case "CREATE_TRAINER":
console.log("payload", payload);
return [
...state,
{ id: uuid(), name: payload.name, team: payload.team ?? [] },
];
case "ADD_TEAM":
return state.map((trainer) =>
trainer.id === payload.id ? { ...trainer, ...payload.team } : trainer
);
default:
return state;
}
};

请试试这个:创建var或const数组

const arrayData = [{
name: 'ron',
team: ['josh','brian'],
},
{
name: 'marie',
team: ['ann', 'kevin']
}
];

然后通过action将这个数组发送给相关的方法。

import {v4 as uuid} from 'uuid';
const initalState = [
{
id: uuid(),
name: ''
}
];


const trainerReducer = (state = initalState, action) => {
const {type, payload} = action;
const arrayData = payload.arrayData;
switch (type) {
case 'CREATE_TRAINER':
console.log('payload', payload);
return [...state,[...arrayData], {id: uuid(), name: payload.name}];

...
...
...

相关内容

  • 没有找到相关文章