将状态传递给另一个组件的正确方法

时间:2020-03-02 22:35:17

标签: javascript reactjs react-router

我正在向应用程序中的不同页面添加一些授权检查,但是在传递某种状态时会遇到一些错误。

我有

const RequireAuth = Component => {
  return class App extends React.Component {
    state = {
      isAuthenticated: false,
      isLoading: true
    };
    _updateLogin = () => {
      this.setState({ isAuthenticated: true, isLoading: false });
    };

    render() {
      const { isAuthenticated, isLoading } = this.state;
      if (isLoading) {
        return <div>Placeholder for animation</div>;
      }
      if (!isAuthenticated) {
        return <Redirect to="/auth/login-page" />;
      }
      return <Component {...this.props} />;
    }
  };
};

我正在尝试将_updateLogin函数传递给AdminLayout组件,该组件具有一个登录页面。

ReactDOM.render(
  <Router history={hist}>
    <Switch>
      <Route
        path="/admin"
        component={RequireAuth(AdminLayout)}
        login={() => {this._updateLogin}}
      />
      <Route path="/auth" component={AuthLayout} />
      <Redirect from="/" to="/admin/dashboard" />
    </Switch>
  </Router>,
  document.getElementById("root")
);

如果运行上面的代码,我将得到

  Line 43:23:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

如果我将登录名更改为

login={this._updateLogin}

返回

"Cannot read property '_updateLogin' of undefined.

有什么提示吗?

0 个答案:

没有答案
相关问题