我已将react路由器设置为从“ /”路由重定向到自定义路由/: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;
答案 0 :(得分:1)
您应该使用一种状态进行重定向,
const [redirect, setRedirect] = useState(false)
在e.preventDefault()
中添加handleFormSubmit
,
const handleFormSubmit = (e) => {
e.preventDefault()
setRedirect(true) //set redirect to ture
};
最后,您可以重定向,
return (
<Container>
{redirect && <Redirect to="/:city/posts" />}
...
</Container>
)