【问题标题】:React-Router using a loading page while fetching a DBReact-Router 在获取数据库时使用加载页面
【发布时间】:2017-03-28 19:45:19
【问题描述】:

所以,我使用 React Router 完成了我的应用程序,一切都按预期工作。当用户进入页面时,他会被重定向到加载屏幕,而我的App 组件会获取数据库,并且在获取完成后,用户会被重定向到获取的类别。

/ -> <Loader /> -> /App().state.data[0].category.

提取速度如此之快,以至于用户甚至看不到加载屏幕,正如预期的那样。所以用户体验。

/ -> /App().state.data[0].category.

所以我的问题是,当用户在/App().state.data[0].category 页面上时,他点击后退按钮,他会看到并停留在加载屏幕上。所以他基本上必须双击才能回到上一页。这是不希望的。

用户体验什么

/App().state.data[0].category -> <Loader /> -> Page before entering the "/"

用户应该体验什么

/App().state.data[0].category -> Page before entering the "/"

我的问题如果用户按下后退按钮,有没有办法跳转加载屏幕?

我开始调查history npm 的事情,我是否走在正确的轨道上?

我当前的配置在伪代码中如下所示:

main.js

render(
  <Router history={hashHistory}>
   <Route path="/" component={App}>
    /* This returns the first category from my api  */
    <IndexRedirect to={App().state.data[0].category} />
    <Route path=":category" component={App} />
   </Route>
  </Router>
,document.getElementById('main'));

App.js

class App extends React.Component{
  componentWillMount() {
    const router = this.context.router;
    fetchData().then(function(results){
      router.push(results.data[0].category);
    })
 }

  render() {
    return (<Loader/>);
 }
}

【问题讨论】:

  • 如果你真的想给加载器一个URL历史记录,你可以尝试window.history.go(-1-numOfLoaders);作为返回按钮,并在添加加载器时增加numOfLoaders。例如,如果您有 1 个加载程序页面,您将获得window.history.go(-2)。但在我所做的情况下,我没有将加载器页面设置为 URL 历史记录。
  • 如果你真的走我的路,你需要对window.history.length做一些错误处理。
  • @AndreLee 我在另一个论坛上发布了这个,一个人告诉我用router.replace 替换router.push。你认为这会解决问题吗?我也会试试你的解决方案。 编辑:当我说后退按钮时,我指的是网络浏览器上的那个
  • 是的,router.replace() 应该是比我的解决方案更好的那个。突然忘记了。

标签: api redirect reactjs react-router


【解决方案1】:

为什么不对单个组件进行条件渲染。

如果数据库 -> 渲染页面

else -> 渲染加载器

一旦你的 db 提取完成,渲染就会挂载,你会看到你的页面而不是你的加载器

【讨论】:

    猜你喜欢
    • 2011-11-13
    • 2019-01-05
    • 2018-03-30
    • 2022-09-23
    • 1970-01-01
    • 2022-01-14
    • 2019-10-21
    • 2018-01-31
    相关资源
    最近更新 更多