首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用React-Router-4,如何以编程方式设置索引路由`/`

使用React-Router-4,如何以编程方式设置索引路由`/`
EN

Stack Overflow用户
提问于 2017-06-26 22:19:02
回答 3查看 844关注 0票数 1

使用-4\f25 React-Router-4 \f6如何以编程方式设置索引路由-4\f25 /

例如,如果用户未通过身份验证,则应触发:

代码语言:javascript
复制
<Route path="/" component={LandingPage}>

如果用户已通过身份验证:

代码语言:javascript
复制
<PrivateRoute path="/dashboard" component={Dashboard} />

有关PrivateRoute的信息,请参阅

更新的尝试

代码语言:javascript
复制
const WithMainLayout = ({component: Component, ...more}) => {
  return <Route {...more} render={props => {
    return (
      <MainLayout {...props}>
        <Component {...props} />
      </MainLayout>
    );
  }}/>;
};

const isLoggedIn = () => {
  console.log('do it')
  return true;
};


....

<WithMainLayout exact path="/" component={Home} render={() => (
  isLoggedIn() ? (
    <Redirect to="/dashboard" />
  ) : (
    <Home />
  )
)}/>

查看上面的尝试,由于某些原因,console.log不会在isLoggedIn函数中输出任何内容。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-06-26 23:44:30

所以在你的更新代码中,问题是你返回

<Route {...more} render={props => {

因此,实际上发生的是,传递给WithMainLayout组件的render属性被您的自定义属性所覆盖,因此永远不会调用isLoggedIn

解决方案很简单,您只需交换{...more}render={props => {}},还可以用WithMainLayout包装Home组件,这样它就不会错过布局

您的代码将如下所示

代码语言:javascript
复制
const WithMainLayout = ({component: Component, ...more}) => {
  return <Route render={props => {
    return (
      <MainLayout {...props}>
        <Component {...props} />
      </MainLayout>
    );
  }}  {...more} />;
};

const isLoggedIn = () => {
  console.log('do it')
  return true;
};


....

<WithMainLayout exact path="/" component={Home} render={() => (
  isLoggedIn() ? (
    <Redirect to="/dashboard" />
  ) : (
    <WithMainLayout component={Home} />
  )
)}/>
票数 2
EN

Stack Overflow用户

发布于 2017-06-26 22:26:40

您可以使用history属性。你可以在这里阅读到:https://reacttraining.com/react-router/web/api/history

本质上,您将组件包装在withRouter HOC中,它将把history属性传递给您的组件,您将在此处看到:https://reacttraining.com/react-router/web/api/withRouter。它与React Recompose非常好地融合在一起。我修改了react路由器文档的“基本示例”,将其作为在history属性中使用withRouter的示例

代码语言:javascript
复制
// create-react-app test && cd test && npm i && npm install react-router-dom
// replace contents of App.js then `npm run start`
import React, { Component } from 'react';
import { withRouter } from 'react-router'
import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'

class BasicExample extends Component {
  render() {
    return(
      <Router>
        <div>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/about">About</Link></li>
          </ul>
          <hr/>
          <Route exact path="/" component={withRouter(Home)}/>
          <Route path="/about" component={About}/>
        </div>
      </Router>
    )
  }
}

class Home extends Component {
  render() {
    const {history} = this.props;
    const handleClick = (e) => {
      history.push("/about")
    }
    console.log(history)
    return (
      <div>
        <h2>Home</h2>
        <button onClick={handleClick}>To about</button>
      </div>
    )
  }
}

const About = () => (
  <div>
    <h2>About</h2>
  </div>
)

export default BasicExample;

如果要在JSX中创建链接,请使用Link组件,如下所示

代码语言:javascript
复制
<Link to="/">...</Link>

如果您是在PrivateRoute组件中执行此操作,我认为您需要的是更像Redirect组件的东西:https://reacttraining.com/react-router/web/api/Redirect

代码语言:javascript
复制
  const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      props.isAuthorized ? (
        <Component {...props}/>
      ) : (
        <Redirect to={{
          pathname: '/',
          state: { from: props.location }
        }}/>
      )
    )}/>)
票数 1
EN

Stack Overflow用户

发布于 2017-06-26 22:29:30

我会将onEnter方法放在IndexRoute上,并根据需要以编程方式将用户发送到正确的位置:

代码语言:javascript
复制
<IndexRoute onEnter={handlePath}>

其中处理程序如下所示,用适当的代码替换userIsAutheticaed

代码语言:javascript
复制
function handlePath(route, replace) {
   if (userIsAuthenticated) {
          replace('/dashboard');
   } else {
          replace('/');
   }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44761854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档