【发布时间】:2021-12-07 08:02:13
【问题描述】:
我正在尝试处理两个表单输入值并保存数据以在提交时使用 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.
提前致谢!
【问题讨论】:
-
我认为如果您在问题中添加最重要的代码部分会更好,只是为了防止链接内容出现问题
-
哦,对不起!不知道,谢谢。我的错!
标签: reactjs input use-state redux-toolkit multiple-input