使用 React Redux Toolkit 处理多个输入值

Handle multiple input values with React Redux Toolkit

我正在尝试处理两个表单输入值并保存数据以在提交时使用 Redux Toolkit 进行存储。看起来很简单,但还没有真正掌握它。

我的第一个想法是使用 useState 将输入值保存在本地,并将数据设置为仅在提交表单时存储。只是为了防止在输入更改时呈现。但是在提交的时候我想把它保存到商店。

export default function App() {
  const [user, setUser] = useState({
    length: null,
    width: null
  });
  const dispatch = useDispatch();

  const handleChange = (e) => {
    const { name, value } = e.target;
    setUser({ ...user, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    // set data to store on submit
    dispatch(setUser);
    console.log(setUser);
  };

  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          name="length"
          onChange={handleChange}
          placeholder="Add Length"
        />
        <input
          type="text"
          name="width"
          onChange={handleChange}
          placeholder="Add Width"
        />
        <button type="submit">Submit</button>
      </form>
      <User />
    </div>

这是我的切片函数:

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

export const userSlice = createSlice({
  name: "user",
  initialState: {
    length: null,
    width: null
  },
  reducers: {
    setUser: (state, action) => {
      state.user.length = action.payload;
      state.user.width = action.payload;
    }
  }
});

export const { user, setUser } = userSlice.actions;
export const selectUser = (state) => state.user;
export default userSlice.reducer;

我设法让它在一个输入下工作,但在有多个输入时就不行了。 See codesandbox for full example.

提前致谢!

您在这里调度具有空值的 setUser 操作

  const handleSubmit = (e) => {
        e.preventDefault();
        // set data to store on submit
        dispatch(setUser);
        console.log(setUser);
      };

改成这样

  const handleSubmit = (e) => {
        e.preventDefault();
        // set data to store on submit
        dispatch(setUser(user));
        console.log(setUser);
      };

然后在userSlice.js中改成这样。

 reducers: {
    setUser: (state, action) => {
      state.length = action.payload?.length;
      state.width = action.payload?.width;
    }
  }

here is the codesandbox link