【问题标题】:How to add data into array of redux store, which will be created dynamically?如何将数据添加到将动态创建的 redux 存储数组中?
【发布时间】:2021-04-28 06:45:26
【问题描述】:

我正在开发嵌套的 todo 应用程序,我的商店中有 todos 数组。当我调度一个动作时,{task:todo, id:id, singletodo:[]} 将被创建。我已经根据 id 完成了路由,每当我点击任何待办事项时,它都会将我带到那个特定的待办事项。我创建了另一个reducer,它将主待办事项的新子待办事项添加到单待办事项数组中。我尝试了各种方法,但似乎没有任何效果。我在 sn-p 中附加代码。

减速机:

 ADD_TODO: (state, action) => {
      state.todos.push(action.payload);
    },
    ADD_Single_TODO: (state, action) => {
      state.todos.singletodo.push(action.payload);
    },

添加待办事项的调度动作:

  function handleFormSubmit(e) {
    e.preventDefault();
    dispatch(ADD_TODO({ task: tasks, id: cuid(),singletodo: [] }));
  }

添加子待办事项的调度动作:

  let single = (e)=>{
    e.preventDefault();
    //todo array from store
    let alldata = useSelector(selectdata);
    //id for main todo
    const id = props.match.params.id;
    alldata.map((todo) => {
      if(todo.id === id) {
        dispatch(ADD_Single_TODO({ task: tasks, id: cuid() }));
      }
    })
  }

【问题讨论】:

  • 请创建一个minimal reproducible example,使用类似代码框的东西
  • todos array in my store 那么为什么你有todos.singletodo
  • 如何将数据推送到 singletodo 数组中? todos 数组的每个对象都包含 singletodo 数组,我正在尝试在 singletodo 数组中为各个对象或各个 todo 推送子 todo
  • 1.不要改变状态,即不要使用push (state.todos.push) 2. 不要使用.map。使用forEach 进行循环(尝试查找匹配项时尝试.find)。

标签: javascript reactjs redux


【解决方案1】:

我解决了这个问题。我在 reducer 和 dispatch action 中都做了修改。

更新减速器:

ADD_TODO: (state, action) => {
      state.todos.push(action.payload);
    },
    ADD_Single_TODO: (state, action) => {
        state.todos.map((todo)=>{
          if(todo.id === action.payload.id ){
            todo.singletodo.push(action.payload)
          }
        })

    },

更新的调度动作:

 let single = ()=>{
    dispatch(ADD_Single_TODO({ task: tasks, id: props.match.params.id, newid:cuid() }))
    setTasks('')
  }

【讨论】:

    【解决方案2】:

    在像您在此处编写的遗留 Redux 中,不允许您对 redux 管理的数据使用 .push 和其他变异函数(请参阅 https://doesitmutate.xyz/ )。 这是 redux 的三个核心原则之一(请参阅 https://redux.js.org/understanding/thinking-in-redux/three-principles#state-is-read-only ),并且会导致许多错误,例如反应不正确重新渲染等。

    您将不得不编写更复杂的不可变更新逻辑,或者 - 我建议 - 遵循官方 redux 教程(https://redux.js.org/tutorials/essentials/part-1-overview-concepts)并学习现代 redux,它为您抽象了“不变性”部分并允许您也使用变异逻辑。

    【讨论】:

      猜你喜欢
      • 2013-04-16
      • 2011-11-19
      • 2020-01-13
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多