[英]Redirect is not working for react-router in a single component
我已將反應路由器設置為從 "/" 路由重定向到自定義路由 /:city/posts ,但重定向未按預期工作,按鈕頁面刷新的 onClick ,我已將其設置在其他組件中正常工作,不確定是什么是問題
沙箱: https : //codesandbox.io/s/focused-sammet-eitqr
import React, { useState } from "react";
import {
Form,
Container,
Button,
DropdownButton,
Dropdown
} from "react-bootstrap";
import { Redirect } from "react-router-dom";
const Location = () => {
let [city, setCity] = useState("");
let [acceptedTOS, setAcceptedTOS] = useState(false);
const handleFormSubmit = () => {
// if (city !== "" && acceptedTOS === true) {
return <Redirect to="/city/posts" />;
// }
};
console.log("city ====", city, "acceptedTOS===", acceptedTOS);
return (
<Container>
<Form onSubmit={handleFormSubmit}>
<h3>Select a City</h3>
<br />
<DropdownButton
id="dropdown-basic-button"
title={city !== "" ? city : "Canada"}
>
</DropdownButton>
<br />
<Form.Group>
<Form.Check
required
name="terms"
label="I have read and agreed to follow TOS"
onChange={() => {
setAcceptedTOS(true);
}}
// isInvalid={!!errors.terms}
// feedback={errors.terms}
id="validationFormik0"
/>
<Button type="submit">Submit form</Button>
</Form.Group>
</Form>
</Container>
);
};
export default Location;
您應該使用狀態進行重定向,
const [redirect, setRedirect] = useState(false)
在handleFormSubmit
添加e.preventDefault()
,
const handleFormSubmit = (e) => {
e.preventDefault()
setRedirect(true) //set redirect to ture
};
最后在你的回報中,你可以重定向,
return (
<Container>
{redirect && <Redirect to="/:city/posts" />}
...
</Container>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.