如何访问组件外部的状态

时间:2018-11-29 15:22:21

标签: reactjs state router

我有一个App组件,我正在尝试制作如下的PrivateRoute:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      this.state.auth === true ? <Component {...props} /> : <Redirect to="/" />
    }
  />
);

问题是this.state.auth在App组件内部,而Route在组件外部,因此我无权访问它,如何从状态中获取布尔值?

PS。你不明白这个问题: 这是我要澄清的代码:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  Switch
} from 'react-router-dom';
import './App.scss';
import ChangePass from './components/ChangePass';
import MManager from './components/MManager';
import Mworker from './components/Mworker';
import Mclient from './components/Mclient';
import Login from './components/Login';
const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      this.state.auth === true ? <Component {...props} /> : <Redirect to="/" />
    }
  />
);

class App extends Component {
  state = {
    id: '',
    password: '',
    role: '',
    token: '',
    firstName: '',
    lastName: '',
    auth: false,
    error: false
  };

您可以看到状态在App组件内部,我想在PrivateRoute中访问它,该怎么做?

3 个答案:

答案 0 :(得分:1)

为了在子组件中使用父状态,应将其作为prop传递:

<PrivateRoute auth={this.state.auth} component={...} />

如果组件深度嵌套,这可能是个问题。

或者,应使用全局状态的解决方案(上下文API,Redux等)来访问嵌套组件中的全局应用程序状态。

答案 1 :(得分:1)

通过道具将状态传递到您的路线/私人路线组件中:

<App>
   <PrivateRoute authed={this.state.auth} ... />
</App>

并在下面访问它:

const PrivateRoute = ({ component: Component, authed, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      authed === true ? <Component {...props} /> : <Redirect to="/" />
    }
  />
);

答案 2 :(得分:-1)

您可以使用ref

<PrivateRoute ref={i => this.my_ref = i} />

代码中的某个地方

console.log(this.my_ref.state)