[英]How can i redirect on submitting my form in reactjs and using formik
the redirect is not working, how can I redirect am using functional components.重定向不起作用,如何使用功能组件进行重定向。
const [redirect,setredirect]=useState(false);
const onSubmit = (values,{resetForm}) => {
console.log('Form data', values);
setredirect(true);
if(redirect)
{
return <Redirect to='/' />
}
You can use history.push
to redirect.您可以使用
history.push
进行重定向。
const history = useHistory()
history.push('/')
Btw, the condition to check if redirect
is true won't work since setRedirect
is asynchronous.顺便说一句,检查
redirect
是否为真的条件将不起作用,因为setRedirect
是异步的。 You don't need the redirect
piece of state at all.您根本不需要 state 的
redirect
部分。
const onSubmit = async (values) => {
// Send an API request with the values
// await makeAPICall(values)
history.push('/')
};
The problem is that setting the state does not (necessarily) change it synchronously, so if you check the state right after you set it, it may still contain the old value.问题是设置 state 不会(必然)同步更改它,因此如果您在设置后立即检查 state,它可能仍包含旧值。 In react, setting the state does not immediately mutate the state, but creates a pending state transition.
在反应中,设置 state 不会立即改变 state,但会创建待处理的 state 转换。 If you need to reliably access the new state right after setting it, just save it to a temporary variable:
如果您需要在设置后立即可靠地访问新的 state,只需将其保存到临时变量:
let shouldRedirect = true; // I'm assuming this is not hard-coded or the if statement makes no sense.
setredirect(shouldRedirect);
if (shouldRedirect) {
// Do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.