您如何通过反应路由器传递道具?

时间:2020-07-23 04:07:43

标签: javascript reactjs react-router react-router-dom

import React, { Component } from 'react';
import {
    Route,
    BrowserRouter as Router,
    Switch,
    Redirect
} from "react-router-dom";
import Landing from './Pages/Landing';
import FourInARow from "./Pages/fourinarow";
import logo from './logo.svg';
import './App.css';

function PublicRoute({ component: Component, mode, ...rest}){
    console.log(...rest)
    return (
        <Route
            {...rest}
            render={ (props) => mode !== null
                ? <Component {...rest} />
                : <Redirect to={'/fourinarow'}/>
            }
        />
    );
}


export default class App extends Component {
    constructor(){
        super();
        this.state = {
            mode: null
        }
    }
    setMode = (mode) => {
        this.setState({mode: mode});
        console.log('click');
    }

    render(){
        return (
            <div className="App">
                <Router>
                    <Switch>
                        <Route exact path='/'
                               render={(props) => <Landing setMode={this.setMode}/>}/>
                        <PublicRoute
                            path='/fourinarow'
                            component={FourInARow}
                            mode={this.state.mode}/>
                    </Switch>
                </Router>

            </div>
        );
    }
}

我正在尝试通过我的PublicRoute函数传递道具,以期以后添加需要身份验证的privateRoute函数。除了传递道具外,这两个功能对于所有其他功能均应正常工作。路线组件已经在传递道具。

1 个答案:

答案 0 :(得分:1)

我看到的一件事是在PublicRoute中,您正在用道具破坏mode...rest,但没有将modeprops传递到{{ 1}}。