简体   繁体   中英

How do you pass props through react router?

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

I am trying to pass props through my PublicRoute function with the hopes of later adding a privateRoute function that requires authentication. Both of these functions work as should for everything but passing props. The Route component is already working to pass props.

One thing I see is in PublicRoute you are destructuring mode and ...rest out of props but you are not passing mode or props into Component .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM