React路由器历史推送总是路由到404页面 [英] React router history push always route to 404 page

查看:34
本文介绍了React路由器历史推送总是路由到404页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

js 并面临使用 react router dom 的困难.我想在单击导航抽屉组件中的按钮时更改路线.

这是我的 App.js 组件.

import { Router, Route, Switch } from "react-router-dom";功能应用(){const 类 = useStyles();返回 (<提供者商店={商店}><div className={classes.root}><导航栏/><抽屉/><路由器历史={历史}><开关><Route path="/" 精确组件={Login}></Route><Route path="/country" 精确组件={Country}></Route><Route path="/user-create" 精确组件={User}></Route><Route path="/countries" 精确组件={ListView}></Route><路由组件={NotFound}></Route></开关></路由器>

</提供者>);}

这里我将 history prop 传递给 Router 组件.History.js

import { createBrowserHistory } from 'history';导出默认 createBrowserHistory();

Drawer.js

从'../../history'导入历史const onRoute = (path) =>{history.push("/user-create");//props.toggleDrawer();}

在 Drawer.js 中,它总是路由到 NotFoundComponet.为什么会发生这种情况?

解决方案

在你的 NavBar 和 Drawer 组件中包括以下 withRouter 或 alt useHistory 钩子来访问历史道具.

import { withRouter } from 'react-router'...this.props.history.push('/user-create')...导出默认 withRouter(...

js and facing hard time with react router dom. I want to change the route when I click a button in my navigation drawer component.

This is my App.js component.

import {  Router, Route, Switch } from "react-router-dom";

function App() {
  const classes = useStyles();
  return (
    <Provider store={store}>
    
        <div className={classes.root}>
          <NavBar />
          <Drawer />
          <Router history={history}>
            <Switch>
              <Route path="/" exact component={Login}></Route>
              <Route path="/country" exact component={Country}></Route>
              <Route path="/user-create" exact component={User}></Route>
              <Route path="/countries" exact component={ListView}></Route>
              <Route component={NotFound}></Route>

            </Switch>
          </Router>
        </div>
     
    </Provider>
  );
}

And here I pass history prop to the Router component. History.js

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

Drawer.js

import history from '../../history'

 const onRoute = (path) => {
    
    history.push("/user-create");
    // props.toggleDrawer();
  }

In Drawer.js it is always route to the NotFoundComponet. Why could this happen?

解决方案

In your NavBar and Drawer components include the below withRouter or the alt useHistory hook to get access to the history prop.

import { withRouter } from 'react-router'
...
this.props.history.push('/user-create')
...
export default withRouter(...

这篇关于React路由器历史推送总是路由到404页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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