首页 > 解决方案 > react-redux,使用一个操作从两个输入字段中更改对象键/值

问题描述

我正在尝试通过一项操作更改对象中的输入值。因此该操作在其类型时从每个输入中获取 key("title" 和 "content") 值作为参数。它fillernote数组对象id匹配activeIdconst 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;
  }
}

标签: javascriptreactjsreduxreact-reduxspread-syntax

解决方案


您可以使用地图并尝试如下

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;
  }
}

推荐阅读