React Router使用React Redux渲染空白页面

时间:2018-06-27 18:14:27

标签: javascript reactjs react-router react-redux

在我的 App.js 中,我具有以下内容:

const Index = asyncRoute(() => import('~/pages/index'))
const Register = asyncRoute(() => import('~/pages/register'))
const AddDesign = asyncRoute(() => import('~/pages/add-design'))
const Login = asyncRoute(() => import('~/pages/login'))

class App extends Component {
  render() {
    const { isLoggedIn } = this.props;

    if(!isLoggedIn){
      return (
          <Switch>
              <Route path={'/login'} component={Login} />
              <Route path={'/register'} component={Register} />
              <Redirect to={'/login'} />
          </Switch>
      );
    }
    return (
      <Switch>
        <Route exact path='/' component={Index}/>
        <Route exact path='/add-design' component={AddDesign}/>
        <Route exact path="/login" render={() => <Redirect to="/"/>} />
        <Route exact path="/register" render={() =>  <Redirect to="/"/>} />
        <Redirect to={'/'} />
      </Switch>
    );
  }
}

function mapStateToProps({ user }) {
  return {
    isLoggedIn: !!user.token,
  };
}

export default connect(mapStateToProps)(App);

用户登录时,isLoggedIn设置为true,然后尝试将用户重定向回"/"

发生这种情况,但是加载的页面是 public 中的 index.html 文件,而不是Index组件。

我不确定是否会有所作为,但是我的asyncRouteFOUC的一种解决方法:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

import Loading from '~/components/Loading'

class AsyncImport extends Component {
  static propTypes = {
    load: PropTypes.func.isRequired,
    children: PropTypes.node.isRequired
  }

  state = {
    component: null
  }

  _hasClass(target, className) {
     return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
  }

  toggleFoucClass () {
    const root = document.getElementById('root')
    if (this._hasClass(root, 'fouc')) {
      root.classList.remove('fouc')
    } else {
      root.classList.add('fouc');
    }
  }

  componentWillMount () {
    this.toggleFoucClass()
  }

  componentDidMount () {
    this.props.load()
      .then((component) => {
        setTimeout(() => this.toggleFoucClass(), 1)
        this.setState(() => ({
          component: component.default
        }))
      })
  }

  render () {
    return this.props.children(this.state.component)
  }
}

const asyncRoute = (importFunc) =>
  (props) => (
    <AsyncImport load={importFunc}>
      {(Component) => {
        return Component === null
          ? <Loading size="large" />
          : <Component {...props} />
      }}
    </AsyncImport>
  )

export default asyncRoute

任何人都可以解释为什么我的用户被路由但组件未呈现吗?

1 个答案:

答案 0 :(得分:0)

假设使用RR4 试试:

<Route path="/" component={App}>
<IndexRedirect to="/index" />
<Route path="index" component={Index} />

请参阅以下内容以正确使用案例: https://github.com/ReactTraining/react-router/blob/5e69b23a369b7dbcb9afc6cdca9bf2dcf07ad432/docs/guides/IndexRoutes.md