簡體   English   中英

如何使用react-router將頂級組件狀態傳遞給路由?

[英]How do you pass top level component state down to Routes using react-router?

我使用react-router設置了一個React應用程序,該應用程序通過Firebase進行身份驗證。

我有這個工作,但我現在希望能夠從主App組件管理登錄用戶(auth)的狀態,並將其傳遞給子組件,而不必查詢每個組件中的auth狀態。

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory } from 'react-router';
import { createHistory } from 'history';

/*
  Firebase
*/
import Auth from './modules/Auth';
import Helpers from './modules/Helpers';

// Auth.unauth();
/*
  Import app modules
*/
import LogIn from './modules/LogIn';
import LogOut from './modules/LogOut';
import NotFound from './modules/NotFound';
import Register from './modules/Register';
import Dashboard from './modules/Dashboard';
import ResetPassword from './modules/ResetPassword';
import ChangePassword from './modules/ChangePassword';
import MyAccount from './modules/MyAccount';


const App = React.createClass({

  getInitialState: function() {
    return {
      loggedIn: Auth.getAuth(),
      userType: null
    }
  },

  setUserLevel: function(authData) {
    if(authData){
      Auth.child('users/'+authData.uid+'/user_level').once('value',
        (snapshot) => {
          this.setState({ userType: Helpers.getUserType(snapshot.val()) })
        },
        (error) => {
          this.setState({
            userType: Helpers.getUserType(0),
            error: error
          });
        }
      );
    }
  },

  updateAuth: function(loggedIn) {
    // console.log('Updating Auth');

    this.setUserLevel(loggedIn);

    this.setState({
      loggedIn: loggedIn
    })
  },

  componentWillMount: function() {
    Auth.onAuth(this.updateAuth);
  },

  render: function() {

    var regButton = (this.state.loggedIn) ? null : (<Link className="Navigation__link" to="register">Register</Link>);
    var accountButton = (this.state.loggedIn) ? (<Link className="Navigation__link" to="account">My Account</Link>) : null;

    return (
    <div>
      <nav className="Navigation">
        {this.state.loggedIn ? (
            <Link className="Navigation__link" to="/logout">Log out</Link>
          ) : (
            <Link className="Navigation__link" to="/login">Sign in</Link>
        )}
        {regButton}
        {accountButton}
        <Link className="Navigation__link" to="dashboard">Dashboard</Link>
      </nav>
      <div>
      {this.props.children}
      </div>
    </div>);
  }
})


function requireAuth(nextState, replaceState) {
  if (!Auth.getAuth())
    replaceState({ nextPathname: nextState.location.pathname }, '/login')
}

function notWhenLoggedIn(nextState, replaceState) {
  if (Auth.getAuth())
    replaceState({ nextPathname: nextState.location.pathname }, '/dashboard')
}

var routes = (
  <Router history={createHistory()}>
    <Route path="/" component={App}>
      <Route path="/login" component={LogIn} onEnter={notWhenLoggedIn} />
      <Route path="/logout" component={LogOut} onEnter={requireAuth} />
      <Route path="/register" component={Register} onEnter={notWhenLoggedIn} />
      <Route path="/resetpassword" component={ResetPassword} onEnter={notWhenLoggedIn} />
      <Route path="/change-password" component={ChangePassword} onEnter={requireAuth} />
      <Route path="/dashboard" component={Dashboard} onEnter={requireAuth} />
      <Route path="/account" component={MyAccount} onEnter={requireAuth} />
      <Route path="*" component={NotFound} />
    </Route>
  </Router>
)

ReactDOM.render(routes, document.querySelector('#main'));

我現在陷入困境,因為我無法找到將App組件的loggedIn state作為子組件的屬性向下傳遞的方法。

react-router甚至可以實現嗎?

我知道如何使用React.Children實用程序的最佳方式。 這是一個快速的Codepen,可以看到實際的概念。 http://codepen.io/anon/pen/RrKbjZ

因此,示例中App組件的render()函數中的代碼看起來像這樣。

render: function() {

  var regButton = (this.state.loggedIn) ? null : (<Link className="Navigation__link" to="register">Register</Link>);
  var accountButton = (this.state.loggedIn) ? (<Link className="Navigation__link" to="account">My Account</Link>) : null;
  var childrenWithProps = React.Children.map(this.props.children, (Child, i) => {
    return React.cloneElement(Child, {
      loggedIn: this.state.loggedIn
    });
  });

  return (
    <div>
      <nav className="Navigation">
        {
          this.state.loggedIn ? 
          (<Link className="Navigation__link" to="/logout">Log out</Link>) :
          (<Link className="Navigation__link" to="/login">Sign in</Link>)  
        }
        {regButton}
        {accountButton}
        <Link className="Navigation__link" to="dashboard">Dashboard</Link>
      </nav>
      <div>
        {childrenWithProps}
      </div>
    </div>
  );
}

我之前有同樣的問題。 這個問題可能對您有所幫助

https://github.com/rackt/react-router/issues/1857

但是,建議不要使用此方法來傳遞參數,尤其是在構建大型應用程序時。

我推薦一些js的狀態管理器,比如“Redux”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM