React:我想提交一个表单,并想通过钩子(useSelector和useDispatch(将数据保存在redux存储中如果需要其他东西,请告诉我,我会上传在这个问题上我需要帮助我会很感激
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import {
Button,
Form,
FormGroup,
Label,
Input,
Container,
Col
} from "reactstrap";
import "./style.scss";
import { addUserAction } from "../../store/reducers/registerReducer.js";
const Register = () => {
const [user, setUser] = useState("");
const usedispatch = useDispatch();
const addUser = user => usedispatch(addUserAction(user));
const submitHandler = e => {
e.preventDefault();
console.log(user);
if (user.trim() === "") return;
addUser(user);
};
const onChange = e => {
//console.log(e.target.value);
setUser(e.target.value);
};
return (
<Container className="register">
<h2>Register</h2>
<Form onSubmit={submitHandler} className="form">
<Col>
<FormGroup>
<Label>Full Name</Label>
<Input
type="text"
name="fullname"
id="fullname"
value={user.fullname}
placeholder="Full Name"
onChange={onChange}
/>
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label>Email</Label>
<Input
type="email"
name="email"
value={user.email}
id="email"
placeholder="myemail@email.com"
onChange={onChange}
/>
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label for="examplePassword">Password</Label>
<Input
type="password"
name="password"
value={user.password}
id="password"
placeholder="********"
onChange={onChange}
/>
</FormGroup>
</Col>
<Button>Submit</Button>
</Form>
</Container>
);
};
export default Register;
//////////////////////////////////////////////////////////////// reducer
const initialState = {
fullname: "",
email: "",
password: ""
};
function userRegister(state = initialState, action) {
switch (action.type) {
case "ADD_USER":
return {
...state
};
default:
return state;
}
}
export default userRegister;
// Actions
export const addUserAction = user => ({
type: "ADD_USER",
payload: user
});
React:我想提交一个表单,并希望通过钩子(useSelector和useDispatch(将数据保存在redux存储中如果需要其他东西,请告诉我,我会上传在这个问题上我需要帮助我会很感激
您的user
状态是一个字符串,并作为字符串更新。但您正在将其作为对象user.fullname
进行访问。
其次,您提交的redux操作带有一个空的用户对象,而不是表单值:
addUser({
fullname: "",
email: "",
password: ""
});
将表单更改为对每个值使用不同的useState
,或者将当前user
状态更改为对象。然后改为发送该对象:
const [user, setUser] = useState({
fullname: "",
email: "",
password: ""
});
const onChange = e => {
setUser({...user, [e.target.name]: e.target.value});
};
addUser(user);
最后,您并没有在reducer中使用有效负载,只是返回状态。通过如下返回来保存用户:
case "ADD_USER":
return action.payload;
<Input
type="email"
name="email"
value={user.email}
id="email"
placeholder="myemail@email.com"
onChange={onChange}
/>
我应该把什么放在这里的价值