gpt4 book ai didi

reactjs - 自定义历史记录不起作用的 react 路由器

转载 作者:行者123 更新时间:2023-12-04 11:06:23 29 4
gpt4 key购买 nike

当我从 react-router-dom 使用 BrowserRouter 时,我的路由正在工作。但是为了使用自定义历史记录,我用来自 react-router 的 Router 替换了 BrowserRouter。之后,我的 Route 组件无法正确加载,但 url 正在正确更改。
这是我的代码:

AppRouter-JS:----

import React from 'react';
import { Router, Route, Switch} from 'react-router';
// import { BrowserRouter as Router,Route, Switch} from 'react-router-dom';
import {createBrowserHistory} from 'history'

import Header from '../components/Header.js';
import Dashboard from '../components/DashboardPage.js'
import CreateExpense from '../components/CreateExpensePage.js';
import EditExpense from '../components/EditExpensePage.js';
import Help from '../components/HelpPage.js';
import PageNotFound from '../components/PageNotFound.js'
import LoginPage from '../components/LoginPage.js'


export const history = createBrowserHistory();

const AppRouter = ()=>(
<Router history={history}>
<div>
<Header/>
<Switch>
<Route path='/' exact={true} component={LoginPage}/>
<Route path='/dashboard' component={Dashboard}/>
<Route path='/create' component={CreateExpense} />
<Route path="/edit/:id" component={EditExpense}/>
<Route path='/help' component={Help} />
<Route component={PageNotFound}/>
</Switch>
</div>
</Router>
)
export default AppRouter;

HeaderJS:-- (这里我们有 NavLinks)
import React from 'react';
import {NavLink, Link} from 'react-router-dom';
import {connect} from 'react-redux';

import {LogoutAction} from '../Redux/Actions/AuthActions.js'

export const Header = ({logoutAction})=>(
<header>
<h1>Expense Tracker</h1>
<p><NavLink exact activeClassName='active-class' to='/'>Home Page</NavLink></p>
<p><NavLink activeClassName='active-class' to='/create'>Add Expense</NavLink></p>
<p><NavLink activeClassName='active-class' to='/help'>Help Page</NavLink></p>
<button onClick={logoutAction}>Logout</button>
</header>
);

const mapDispatchToProps = (dispatch)=> {
return {
logoutAction: ()=> dispatch(LogoutAction())
}
}

export default connect(undefined,mapDispatchToProps) (Header);

单击任何 NavLink 或 Link 后,它始终会打开 PageNotFound 组件。

最佳答案

我实际上刚刚发现了我的问题,它也可能是你的问题。
我在 react-router-dom@5.2.0history@5.0.0 .
react-router 5x 与 history 4x 兼容。一旦我降级到history@4.10.1一切都开始工作了。

关于reactjs - 自定义历史记录不起作用的 react 路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62449663/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com