如何在React中提交表单后重定向用户



我有一个react项目,它在文件中定义了一个注册元素。代码是

import React, { Component } from 'react';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import { useNavigate } from 'react-router-dom';
import postData from './APIREQ';
class Signup extends Component {
state = {
email: "",
password: ""
};
onSubmit = (e) => {
e.preventDefault();
console.log(this.state.email);
console.log(this.state.password);
postData('http://localhost:5000/users', { email: this.state.email, password: this.state.password })
.then(data => {
console.log(data);
const navigate = useNavigate();
navigate('/');


});
}

render() {

return (
<div className="container">
<Form>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" value={this.state.email} onChange={e => this.setState({ email: e.target.value})}/>
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Password" value={this.state.password} onChange={e => this.setState({ password: e.target.value})}/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Check me out" />
</Form.Group>
<Button variant="primary" type="submit" onClick={this.onSubmit}>
Submit
</Button>
</Form>
</div>
);
}
}

export default Signup;

提交表单时,我想重定向到主页(托管在/)。但是,当前代码给出了

的错误。
react-dom.development.js:16063 Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
at Object.throwInvalidHookError (react-dom.development.js:16063:1)
at useContext (react.development.js:1613:1)
at useInRouterContext (hooks.tsx:61:1)
at useNavigate (hooks.tsx:140:1)
at Signup.js:22:1

我看了每一个搜索结果,但没有一个工作。它给出的链接说它们必须在函数组件的主体中调用,但是我如何在保持状态的同时使其成为函数组件?谢谢!

要使用钩子(如useNavigate等),您应该使用function components。对于存储状态,还可以使用useState,例如:

const Signup = () => {
const [state, setState] = useState({
email: '',
password: ''
});

const navigate = useNavigate();

const onSubmit = (e) => {
e.preventDefault();
console.log(state.email, state.password);

postData('http://localhost:5000/users', { email: state.email, password: state.password })
.then(data => console.log(data));

navigate('/');
};
return (
<div>
<SomeComponent />
// .. and code.
</div>
);
}

最新更新