为什么在React-Router-Dom的Router中需要“历史记录"? [英] Why is 'history' necessary in the Router of React-Router-Dom?

查看:82
本文介绍了为什么在React-Router-Dom的Router中需要“历史记录"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我们使用 react-router-dom 库来导航到每个页面.用法通常与以下用法相同,与 create-react-app 创建的用法相同.

Normally, we use react-router-dom library in order to navigate to each page. The usage is normally just like following and it is the same as what created by create-react-app.

history.js 文件

import * as history from 'history';

export default history.createBrowserHistory();

index.js 文件

import {Router} from 'react-router-dom';

import history from '../history';

<Router history={history}></Router>

但是我不明白为什么 Router 需要 history .有谁能伸出援手使我理解?

But I don't understand why history is necessary for the Router. Is there anyone who can lend a hand to make me understand?

推荐答案

假设我们显示了用户信息,我们需要添加功能以重定向到/users 路由通过API删除用户后.

Let's imagine that we have the user's info showing, we need to add the functionality to redirect to the /users route after deleting the user through the API.

由于我们需要在API返回响应后进行重定向,因此我们不能仅使用链接返回.我们需要手动执行.React Router通过将历史对象作为道具传递到每个路由中,从而使此操作变得容易.通过此历史记录对象,我们可以手动控制浏览器的历史记录.由于使React Router可以根据当前URL更改看到的内容,因此history对象可以使我们对何时显示应用程序的某些部分进行精细控制.

Since we need to redirect after the API returns a response, we can't just use Link to go back. We need to manually do it. React Router makes this easy by passing a history object into each route as a prop. This history object lets us manually control the history of the browser. Since React Router is made to change what we see based on the current URL, the history object can give us fine-grained control of when and where certain pieces of the application are shown.

要引起我们想要发生的更改,我们需要在浏览器的历史记录上添加一条新路线.React Router将对此进行选择并相应地更新视图.

To cause the change we want to happen, we need to push a new route onto the browser's history. React Router will pick this up and update the view accordingly.

src/fe/components/UserInfo.js 中,将 handleDelete 方法更新为如下形式.

In src/fe/components/UserInfo.js, update the handleDelete method to look like this.

handleDelete() {
  const { match: { params }, history } = this.props;

  axios.delete(`/api/users/${params.userId}`)
    .then(() => {
      history.push('/users');
    });
}

现在尝试删除用户.请注意,删除用户后如何关闭模式,然后回到用户表.那很简单.

Now try deleting a user. Notice how after the user is deleted, the modal is closed, and we are back at the users' table. That was simple.

希望这个答案会有所帮助.:)

Hope this answer is helpful. :)

这篇关于为什么在React-Router-Dom的Router中需要“历史记录"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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