【问题标题】:React-router v4: Conditional expression not executing correctlyReact-router v4:条件表达式未正确执行
【发布时间】:2017-06-13 19:11:57
【问题描述】:

操作系统:Windows 10 专业版
反应路由器:4.1.1
反应:15.5.4

所以,我在 <Route /> 中进行条件检查以确定 authToken 是否存在,如果它不重定向用户登录,否则呈现关联的组件。但即使令牌存在,如图所示,如果您重新加载 root //view/:postId 的页面,用户仍会被重定向到登录页面。

我在这里忽略了什么?

app.js

  render () {
    const SOME_PATH = window.location.pathname;

    return (
      <ApolloProvider store={store} client={client}>
        <Router history={history}>
          <Route path={SOME_PATH} component={App}/>
        </Router>
      </ApolloProvider>
    )
  }

App.js

export default compose(
  allPostsCommentsQuery,
  connect(mapStateToProps, mapDispatchToProps)
)(Main);

Main.js

  render () {
    const auth = this.props.auth.token;
    console.log('auth = ', auth);
    return (
      <div>
        <h1>
          <Link to="/">Flamingo City</Link>
        </h1>
        <Switch>
          <Route path={`${this.props.match.url}`} exact render={(props) => (
            !auth ? <Redirect to="/login"/> : <PhotoGrid {...this.props} {...props} />
          )} />
          <Route path={`${this.props.match.url}view/:postId`} render={(props) => (
            !auth ? <Redirect to="/login"/> : <Single {...this.props} {...props} />
          )} />
          <Route path={`${this.props.match.url}login`} render={(props) => (
            <LoginUser {...this.props} {...props} />
          )} />
        </Switch>
      </div>
    );
  }

【问题讨论】:

  • 我有同样的问题

标签: reactjs react-router react-router-v4 react-router-dom


【解决方案1】:

如下重构代码解决了这个问题:

!auth ? (<Redirect to="/login"/>) : (<PhotoGrid {...this.props} {...props} />)

【讨论】:

    猜你喜欢
    • 2017-11-14
    • 2017-02-20
    • 1970-01-01
    • 2017-10-04
    • 2018-03-12
    • 2021-12-21
    • 2019-10-16
    • 1970-01-01
    • 2018-01-18
    相关资源
    最近更新 更多