<在 React 中注册的重定向问题.js + 节点(快速)+ MongoDB



我正在编写与React.js + Node (express) + MongoDB的注册。我的所有步骤都有效:我的console.log()在前面工作,然后在后面,然后再次在前面。我的"新用户"订阅后在我的数据库(MongoDB)中有很好的记录。所以一切都很好,除了<React的重定向只工作0.2秒。页面立即"跳转"回来。>

的确,我有一个<重定向在不到1秒,但页面又回到了空的新注册。这里是新用户在数据库(很好!),但我的重定向在前面不工作。>

I tried:

return <Redirect to='/home' />
return <Redirect push to='/home' />
return <Link to='/home' />

我觉得这是一个关于@或任何输入中的特殊字符的问题,因为我在没有任何数据库的输入过程中成功了,但这似乎不是原因。

React.js:signup.jsx钩:

const [email, setEmail] = useState('');

然后输入

的例子
<Input
type='email'
style={style.inputEmail}
onChange={(e) => setEmail(e.target.value)}                                         
/>

然后钩子+函数来管理后端

const [userConnected, setUserConnected] = useState(false)

const handleSubmitForm = async () => {

const data = await fetch('/users/form', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: `email=${email}&password=${password}`
})
const body = await data.json();

if(body.integrationBDD){
setUserConnected(true)
}  
}
if(userConnected){
return <Redirect push to='/home' />
}
  • import { Redirect, useHistory } from "react-router-dom";

app.js

<Router>
<div className="page-container">
<NavBar />
<Switch>
<Route exact path="/"  component={Admin} />
<Route exact path="/home"  component={Home} />
..

请注意,当

假设你正在使用react-router,我认为你可以在这里使用useHistory钩子。例如:

const [userConnected, setUserConnected] = useState(false);
const history = useHistory();
const handleSubmitForm = async ()=> {
if(body.integrationBDD){
history.push("/home"); //or history.push("/");
}
}

来源:https://reactrouter.com/web/api/Hooks