redux异步
In react-application
we encounter many scenarios where we want to switch to another route based on API
response. For example when user submits a form, based on success failure we want our application to redirect him to certain specific page. Generally we accomplish this by creating aflag
variable. Which keeps track of our decision whether to redirect or not. We make one state
variable and update it, whether we want a redirection or not. Here is the code sample for the same.
在react-application
我们遇到了许多想根据API
响应切换到另一条路由的场景。 例如,当用户提交表单时,基于成功失败,我们希望我们的应用程序将其重定向到特定的页面。 通常,我们通过创建一个flag
变量来完成此任务。 这将跟踪我们是否重定向的决定。 无论是否需要重定向,我们都使一个state
变量并对其进行更新。 这是相同的代码示例。
Class Version
类版本
Functional Version
功能版本
There is another version where we can leverage the createBrowserHistory
object of history
package which is more cleaner way of achieving this. By using this we can change our Route from async actions. To do so we have to through following process.
还有另一个版本,我们可以利用history
包的createBrowserHistory
对象,这是实现此目的的更createBrowserHistory
的方法。 通过使用此方法,我们可以从异步操作更改路由。 为此,我们必须通过以下过程。
Step 1: Create a file and name it history.js
or history.ts
if you are using typescript. You can give any name you wanted but history
name is suitable for this file.
第1步:创建一个文件,并将其命名为history.js
或history.ts
如果使用打字稿)。 您可以提供任何想要的名称,但history
名称适用于此文件。
Step 2: Place the following content inside it:
步骤2:将以下内容放入其中:
Step 3: Navigate to your root component where you’ve added ‘Router’ . Here you have to import the history
file and pass it to the history
prop of Router.
第3步:导航到添加了“ Router”的根组件。 在这里,您必须导入history
文件并将其传递给Router的history
属性。
Make sure you are importing
Router
fromreact-router-dom
not theBrowserRouter.
If you have an import like thisimport {BrowserRouter as Router} from 'react-router-dom';
change it toimport {Router} from 'react-router-dom';
.确保您是从
react-router-dom
而非BrowserRouter.
导入Router
的BrowserRouter.
如果您有类似的导入,例如import {BrowserRouter as Router} from 'react-router-dom';
将其更改为import {Router} from 'react-router-dom';
。Issue if you don’t do this: Your address bar URL will change but content won’t be rendered. 😒
如果您不这样做,则会出现问题:地址栏URL会更改,但不会呈现内容。 😒
WHY ?🤔 Short Answer Because
BrowserRouter
ignores the history prop as it handles the history automatically for you. If you need access to the history outside of a react component, then usingRouter
should be fine👌🏻 😃为什么?🤔简短答案,因为
BrowserRouter
忽略历史记录道具,因为它会自动为您处理历史记录。 如果您需要访问react组件之外的历史记录,则可以使用Router
Step 4: Use history
in your action file to push routes.
步骤4:使用动作文件中的history
来推送路线。
You’ve successfully changed the Route from Async Redux action.
您已成功更改了“来自异步Redux的路由”操作。
redux异步