【问题标题】:react-redux, change object key/value with parameters from two input fields with one actionsreact-redux,使用一个操作从两个输入字段中更改对象键/值
【发布时间】:2020-05-14 16:21:46
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs redux react-redux spread-syntax


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢@sathish kumar。你的方法效果很好,只是有一个错字const updateReuslt。哦,伙计……这比我想象的要容易。再次感谢您。
    猜你喜欢
    • 2018-02-09
    • 2019-05-03
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多