简体   繁体   English

如何将对象添加到 Redux 减速器中?

[英]How to add objects into Redux reducers?

I'm using Redux with Next JS, and i'm trying to add array of objects to it.我在 Next JS 中使用 Redux,我正在尝试向它添加对象数组。 in my app i have a form with multiple inputs.在我的应用程序中,我有一个包含多个输入的表单。 to create this multiple input i've created an input form of 10.为了创建这个多重输入,我创建了一个 10 的输入表单。

{homeAmeneties.map((home) => {
    <div className="h-8 flex justify-end  rounded-md pr-10">
                    <input
                      type="number"
                      onInput={(event) =>
                        (event.target.value = event.target.value.slice(
                          0,
                          event.target.maxLength
                        ))
                      }
                      maxLength="3"
                      onChange={(e) => updateVal(e, home.name)}
                      className="border-[1px] w-1/2  border-black rounded-md h-full focus:outline-none px-2"
                    />
                  </div>
})}

each of the values from the input is added to an array.来自输入的每个值都被添加到一个数组中。 but i wanted to add it into redux array.但我想将它添加到 redux 数组中。 in my redux reducer i've created在我创建的 redux 减速器中

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  arr: []
}

export const arrSlice = createSlice({
  name: "arrS",
  initialState,
  reducers: {
    setArr: (state, action) => {
      state.arr = [...state.arr, action.payload];
    }
  }
});

//...rest here

when i run this it throws TypeError: action.payload is not iterable , i've tried to add it just by passing as state.arr = action.payload;当我运行它时它抛出TypeError: action.payload is not iterable ,我试图通过传递state.arr = action.payload; and it doesn't store the input as array of objects, just simple object.它不会将输入存储为对象数组,只是简单的 object。

How can i add and make tweeks like i can do it in simple useState?我怎样才能像在简单的 useState 中那样添加和制作 tweeks?

the code below is what i did with regular useState()下面的代码是我对常规useState()所做的

 const [amen, setAmen] = useState([]);

const updateVal = (e, type) => {
    setAmen((prevAmen) => {
      const newAmen = [...prevAmen]; // create a copy of the current state
      const index = newAmen.findIndex((item) => item.name === type); // find the index of the object with the matching name
      if (e.target.value === "") {
        if (index !== -1) {
          newAmen.splice(index, 1);
        }
      } else {
        if (index !== -1) {
          newAmen[index] = { name: type, val: e.target.value }; // update the object at that index
        } else {
          newAmen.push({ name: type, val: e.target.value }); // add a new object to the array
        }
      }
      return newAmen;
    });
    dispatch(setRooms(...amen));
    console.log(rooms);
  };

I found an answer to this if anyone wants a solution.如果有人想要解决方案,我找到了答案。 before that let me explain what it does.在此之前让我解释一下它的作用。

i have an array of objects that's coming from an input fields.我有一组来自输入字段的对象。 and when these fields value changes it trigger the Redux dispatch.当这些字段值更改时,它会触发 Redux 调度。 if the array exists it updates that array if not, well it creates new array.如果数组存在,它会更新该数组,如果不存在,那么它会创建新数组。

the data i have is something like below我拥有的数据如下所示

[
  {name: "name1" , val: 27},
  {name: "name2" , val: 26},
  {name: "name3" , val: 25},
  {name: "name4" , val: 24},
  {name: "name5" , val: 23},
  {name: "name6" , val: 22},
]

and when input onChange() triggers, it dispatch the data to redux. onChange={(e) => handleChange(name, e.target.value)}当输入onChange()触发时,它将数据分派到 redux。 onChange={(e) => handleChange(name, e.target.value)}

const handleChange = (name, val) =>{
  const obj = { name: name, val: val };
  dispatch(setUser(obj))
}

and in the reducer在减速器中

setUser: (state, action) => {
      const newState = [...state.users];
      const type = action.payload;

      const index = newState.findIndex((item) => item.name === type.name);

      if (type.val === "") {
        if (index !== -1) {
          newState.splice(index, 1);
        }
      } else {
        if (index !== -1) {
          newState[index] = { name: type.name, val: type.val };
        } else {
          newState.push({ name: type.name, val: type.val });
        }
      }

      state.users = [...newState];
      console.log(state.users);
    },

hopefully this helps someone.希望这对某人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM