react-router-native <redirect>呈现空白页

时间:2018-07-09 00:56:37

标签: reactjs react-native react-router mobx react-router-native

逻辑似乎很简单,尽管我尝试了六个排列来查看是否有任何变化。我不知道为什么react-router表现为这种方式:

import React from 'react'
import { View, Text } from 'react-native'
import { observer, inject } from 'mobx-react'
import { NativeRouter, Link, Route, Redirect, Switch } from 'react-router-native'

import Welcome from './welcome'
import Tutorial from './tutorial'
import Plants from './plants'

@inject('store')
@observer
class Main extends React.Component {
  render() {
    const newUser = true //this.props.store.plants.length === 0
    const home = newUser ? '/welcome' : '/plants'
    return (
      <Switch>
        <Route path='/plants' component={Plants} />
        <Route path='/tutorial' component={Tutorial} />
        <Route path='/welcome' component={Welcome} />
        <Redirect to={home} />
        <Route path='/' component={Welcome} />
      </Switch>
    )
  }
}

export default Main

最后的“欢迎”应该是不必要的,但是我已经把它放在那儿进行了测试:如果我删除了,那么会出现欢迎,因此很明显,这导致了空白页面的呈现。

这是顶级组件的render()方法:

return (
  <Provider store={store}>
    <NativeRouter>
      <Main />
    </NativeRouter>
  </Provider>
)

这是基于https://reacttraining.com/react-router/native/guides/philosophy上的示例,该示例显示了不带封闭路由器的情况下都使用的Switch,Route和Redirect:

const App = () => (
  <AppLayout>
    <Route path="/invoices" component={Invoices}/>
  </AppLayout>
)

const Invoices = () => (
  <Layout>

    {/* always show the nav */}
    <InvoicesNav/>

    <Media query={PRETTY_SMALL}>
      {screenIsSmall => screenIsSmall
        // small screen has no redirect
        ? <Switch>
            <Route exact path="/invoices/dashboard" component={Dashboard}/>
            <Route path="/invoices/:id" component={Invoice}/>
          </Switch>
        // large screen does!
        : <Switch>
            <Route exact path="/invoices/dashboard" component={Dashboard}/>
            <Route path="/invoices/:id" component={Invoice}/>
            <Redirect from="/invoices" to="/invoices/dashboard"/>
          </Switch>
      }
    </Media>
  </Layout>
)

1 个答案:

答案 0 :(得分:2)

NativeRouter用作Main组件中最顶层的组件,它将按预期工作。

@inject('store')
@observer
class Main extends React.Component {
  render() {
    const newUser = true //this.props.store.plants.length === 0
    const home = newUser ? '/welcome' : '/plants'
    return (
      <NativeRouter>
        <Switch>
          <Route path='/plants' component={Plants} />
          <Route path='/tutorial' component={Tutorial} />
          <Route path='/welcome' component={Welcome} />
          <Redirect to={home} />
        </Switch>
      </NativeRouter>
    )
  }
}