在使用react-router更改路由之前获取数据 [英] fetching data before changing route with react-router

查看:429
本文介绍了在使用react-router更改路由之前获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在后端使用反应反应路由器 redux laravel 我正在使用所有最新版本,而实际上我对这些版本还很陌生,所以我决定将自己的开发经验提升到一个新的水平,并决定根据自己的喜好使用它们,很多.

I'm using react, react-router, and redux with laravel on the backend and I'm using all the latest releases and I'm actually quite new to these, I just decided I should take my development experiences to the next level and decided to use these based on how I liked them, A LOT.

我有以下问题:当我处于关于我们路线时,然后单击 Home ,但在路由器呈现主页之前>,它需要对服务器进行异步调用.我注意到,从理论上讲,我需要将此保持异步状态,因为它需要先完成,然后才能继续进行下一条路线.

I have the following problem: When I am in the about-us route, I then click Home but before router renders the home page, it needs to make an async call to the server. I notice that I theoretically need this to be async because it needs to finish before proceeding to the next route.

然后,我想在页面顶部有一个栏,指示我正在获取服务器上的依赖项.完成后,应继续执行本地路线.

Then, I want to have a bar on the top of the page that indicates that I am fetching dependencies on the server. Once it is done, it should proceed to the home route.

一个实际示例是GitHub,示例您位于代码标签,然后单击问题标签,蓝色加载栏将显示在指示正在获取数据或依赖项的页面,一旦完成,它将呈现下一条路由.我该怎么做?

A practical example is GitHub, example you are on the code tab, then you clicked on the issues tab, a blue loading bar will appear on the very top of the page that indicates that data or dependencies are being fetched then once it's done it will render the next route. How do I do this?

我认为我应该使用某种中间件,因此在路由更改之前,我应该分派一个将获取我需要的依赖项的操作,然后在完成后我应该分派一个将更新部分中间件的操作.在redux商店中,我无法找到一种方法来应用中间件来对路由器进行响应,而且我真的不知道从何处以及如何开始.

I'm thinking I should use some kind of a middleware, so before the route change I should dispatch an action that will fetch the dependencies that I need then once it's done I should dispatch an action that will update some parts of the redux store, I can't find a way to appy a middleware to react-router though and I really don't know where and how to start.

推荐答案

如果您使用的是普通Redux和路由器,则可以使用路由器的生命周期功能,例如 onEnter (在进入视图之前调用)或 onLeave ...",则您可以执行任意操作,并且这些函数在调用时都接受回调函数,实际的路由会发生.

if you're using plain redux and router you can use router's lifecycle functions like onEnter (which is calling before entering the view) or onLeave..., then you can do whatever you like and these are accept an callback function when you call it, actual routing happens.

另一种选择是将一些Redux Promise中间件用于异步作业,例如 redux-promise-middleware 或仅使用 loadingbar 进行 thunk (如我们在生产中使用它们)非常适合异步操作.

another option is using some redux promise middleware for async jobs such as redux-promise-middleware or simply thunk with loadingbar (as we use them in production) which is works perfectly with async actions.

Redux承诺中间件

反应Redux加载栏

这篇关于在使用react-router更改路由之前获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆