javascript React路由器不显示浏览器历史记录

bbuxkriu  于 2023-01-16  发布在  Java
关注(0)|答案(6)|浏览(199)

我正在学习这个tutorial,但我一直得到这个错误:
“react-router”不包含名为“browserHistory”的导出。
包含react-router的文件如下:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';

ReactDOM.render(
  <Router history={browserHistory} routes={routes} />, 
  document.getElementById('root')
);
nbysray5

nbysray51#

现在需要从history模块获取browserHistory

import createHistory from 'history/createBrowserHistory'

请注意,他们最近更改了模块API,因此如果您使用的是最新版本,则导入会略有更改:

import { createBrowserHistory } from 'history'
t9eec4r0

t9eec4r02#

我也遇到了同样的问题,我浪费了几天时间来解决这个问题。这个错误的发生仅仅是因为react-router v4没有browserHistory(我不知道这是不是一件好事)。我通过安装v3解决了这个问题,如下所示:

npm install react-router@3 --save
5fjcxozz

5fjcxozz3#

您使用的是react-router版本4

要么降级软件包,要么按照此SO answer中的说明操作,使其在v4中工作。

r1wp621o

r1wp621o4#

简单解决方案

方法1:

npm install --save history

use this now:

import createHistory from 'history/createBrowserHistory'

方法:2

Use Version 3  

npm install react-router@3
ej83mcc0

ej83mcc05#

import browserHistory from "history/createBrowserHistory";

使用

const routermiddleware = routerMiddleware(browserHistory());
const history = syncHistoryWithStore(browserHistory(), store);
wz3gfoph

wz3gfoph6#

在react-router-dom版本6中,useHistory()useNavigate()替换;

import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/home')

如果react-router-dom版本低于6

import { useHistory } from "react-router-dom";
const history = useHistory();
history.push('/home')

相关问题