如何避免两次重定向(反应)?

时间:2019-01-24 14:49:28

标签: reactjs

我需要消除两次重定向。 从App.js转到Product.js,然后我需要重定向到/ notfound。它可以工作,但是即使在我在那儿实现了Switch的情况下,也可以运行两次。 我在哪里犯错?我只看到了将Switch放在此处的建议,但这无济于事。

有我的代码:

App.js:

import React from 'react';
import './App.css';
import { Route, Switch } from 'react-router-dom';
import Products from './Products';
import NotFound from './NotFound';
import Home from "./Home";

class App extends React.Component {

    render() {
        return (
            <div>
                <Switch>
                    <Route path="/products" component={Products} />
                    <Route path="/notfound" component={NotFound} />
                    <Route path="/" exact component={Home} />
                </Switch>
            </div>
        );
    }
}
export default App;

Product.js:

import React, { Component } from "react";
import { Redirect, Switch } from 'react-router-dom';

class Products extends Component {

    state = {
        toDashboard: false,
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.setState({
            toDashboard: true
        });
    }

    render() {
        console.log(this.props);

        if (this.state.toDashboard === true) {
            return (
                <div>
                    <Switch>
                        <Redirect to={{
                            pathname: '/notfound', state: { id: '123' }
                        }} />
                    </Switch>
                </div>
            );
        }

        return (
            <div>
                <h1>Products</h1>
                <form onSubmit={this.handleSubmit}>
                    <button type="submit">Submit</button>
                </form>
            </div>
        );
    }
}
export default Products;

1 个答案:

答案 0 :(得分:2)

您可以按以下方式使用history.push

if (this.state.toDashboard === true) {
  this.props.history.push({ pathname: '/notfound', state: { id: 123 }})
}