【问题标题】:Redirect is not working for react-router in a single component重定向不适用于单个组件中的 react-router
【发布时间】:2020-04-17 08:14:06
【问题描述】:

我已将反应路由器设置为从“/”路由重定向到自定义路由 /: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;

【问题讨论】:

    标签: javascript html express react-router


    【解决方案1】:

    您应该使用状态进行重定向,

    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>
    )
    

    【讨论】:

    • 先生您为什么选择重定向作为回报而不是句柄形式或组件内的其他功能
    • render 函数是根据状态值重定向的好位置,因为当状态更改时组件会重新渲染。
    猜你喜欢
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2020-12-22
    • 2017-11-10
    • 2014-10-12
    相关资源
    最近更新 更多