react-router将props传递给组件

时间:2017-06-21 00:56:55

标签: reactjs react-router

我有这两个组件,应用程序和登陆。我想将currentUser传递给Landing组件,但道具不能通过我当前的设置传递。这可能与react-router v4有关。我正在努力不使用redux。我只是希望能够将我的登录信息传递给一些具有不同路由的组件。

Application.js

import React, { Component } from 'react';
import { auth, database } from '../firebase';
import { HashRouter, Match } from 'react-router';
import Landing from './Landing';
import SignIn from './SignIn';

import map from 'lodash/map';

class Application extends Component {
  constructor(props) {
    super(props);

    this.state = {
      currentUser: null
    };
  }

  componentDidMount() {
    auth.onAuthStateChanged((currentUser) => {
      console.log('AUTH_CHANGE', currentUser);
      this.setState({ currentUser });

      // redirect to dashboard? 

    });
  }

  render() {
    const { currentUser } = this.state;

    return (
      <div className="Application">
        <header className="Application--header">
          <h1>Site Title</h1>
        </header>

        <HashRouter>
          <div>
            <Match exactly pattern='/' component={Landing} user={currentUser} />
          </div>
        </HashRouter>
      </div>
    );
  }
}

export default Application;

Landing.js

import React, { Component } from 'react';
import { auth, database } from '../firebase';
import CurrentUser from './CurrentUser';
import SignIn from './SignIn';

class Landing extends Component {
    constructor(props) {
        super(props);
    }

    render() { 
        const currentUser = this.props.user;  

        return (
            <div>
                {!currentUser && <SignIn />}
                {
                  currentUser && 
                  <div>
                    <CurrentUser user={currentUser} />
                  </div>
                }
            </div>
        );
    }
}

export default Landing;

2 个答案:

答案 0 :(得分:0)

尝试这样。希望对您有帮助:
<ProtectedRoute user={userStore} path="/transfers/own-card/accepted/:transaction_id" exact component={(props) => (<PaymentCheckPage infoPage={true} {...props} />)} />

答案 1 :(得分:0)

您应该在Route组件中使用render道具(如KA01在注释中指出的那样)。在那里,您可以提供一个返回组件的函数,还可以传递所需的道具:

<Route exact path='/' render={props => <Landing {...props} currentUser={currentUser} />} />