javascript - react-redux,使用一个操作从两个输入字段中更改对象键/值
问题描述
我正在尝试通过一项操作更改对象中的输入值。因此该操作在其类型时从每个输入中获取 key("title" 和 "content") 值作为参数。它filler
与note
数组对象id
匹配activeId
。const noteValue = { [action.key]: action.value };
当我显示具有正确值的对象时分配值console.log
但是,我无法使用扩展运算符返回正确的值。我试过了,map
但它返回了boolean
。所以我认为这不是正确的方法。这对指导很有帮助。谢谢你。
零件
<div key={id}>
<Title
type="text"
defaultValue={title}
onChange={e => editNote("title", e.target.value)}
></Title>
<NoteContent
type="text"
defaultValue={content}
onChange={e => editNote("content", e.target.value)}
></NoteContent>
</div>
行动
export const editNote = (key, value) => ({
type: EDIT_NOTE,
key,
value
});
状态
const initialState = {
notes: [
{
id: "1234",
title: "title 1",
content: "content 1"
},
{
id: "5678",
title: "title 2",
content: "content 2"
},
{
id: "9101112",
title: "title 3",
content: "content 3"
}
],
activeId: null
};
减速器
export default function reducer(state = initialState, action) {
switch (action.type) {
case SET_ACTIVE_ID:
return { ...state, activeId: action.activeId };
case EDIT_NOTE:
const note = state.notes.filter(note => note === state.activeId);
const noteValue = { [action.key]: action.value };
const noteArr = [...note, { ...noteValue }];
console.log(noteArr);
return { ...state, notes: [...state.notes, ...noteArr] };
default:
return state;
}
}
解决方案
您可以使用地图并尝试如下
export default function reducer(state = initialState, action) {
switch (action.type) {
case SET_ACTIVE_ID:
return { ...state, activeId: action.activeId };
case EDIT_NOTE:
const updatedReuslt = state.notes.map((note)=>{
if(note.id === state.activeId){
return {...note, [action.key] : action.value }
} else {
return note;
}
})
return { ...state, notes:updatedResult };
default:
return state;
}
}
推荐阅读
- angular - 使用 .toBeTruthy() 测试函数时,预期在 Karma 单元测试中定义未定义错误
- python - 即使我得到了变量值,我也得到了一个错误(python)
- sdn - Ryu 控制器没有链接
- here-api - 是否可以通过查询 HERE REST-API 获取 EV 充电站的位置数据?
- android - 如何绘制箭头而不是拖动阴影?
- javascript - JQuery 添加类后添加另一个类并且可见
- gdb - 使用 GDB 和 LLDB 在 D 代码中命中代码行断点的问题
- javascript - Node.js:无法读取未定义的属性“then”(嵌套查询)
- apache - 将所有带有参数的 url 从旧域重定向到新域,除了一个 url
- html - HTML如何显示内容