【发布时间】:2023-03-27 05:39:01
【问题描述】:
逻辑似乎很简单,尽管我尝试了六种排列以查看是否有任何变化。我不知道为什么 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 的示例,该示例显示了在没有封闭路由器的情况下使用了交换机、路由和重定向:
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>
)
【问题讨论】:
-
这是期望的行为,但不会发生。相反,它只显示一个空白页。如果我删除重定向(保留默认的“/”以欢迎),那么欢迎按预期呈现,所以我知道欢迎组件正在工作。
-
这令人沮丧。 web equivalent is working fine。您正在导入
NativeRouter,但没有使用它。您是否忘记了它,或者您在Main之外使用它? -
它在顶层使用(并将其上下文向下传递)。
-
感谢@Tholle 的链接和评论,我将
Main组件包装在NativeRouter中,现在它按预期工作。我不知道为什么这是必要的,尽管the docs 建议这不应该是必要的。 -
如果你想用^^回答我会接受;否则我可以用工作代码来回答。
标签: reactjs react-native react-router mobx react-router-native