简体   繁体   English

如何正确使用 react-router

[英]How to correctly use react-router

Somewhat new to react, and liking the library, but running into all kinds of headaches with the router.有点新的反应,喜欢这个库,但遇到了路由器的各种头痛。

Here is my current code, question is below:这是我当前的代码,问题如下:

// routes.js // 路由.js

var React = require('react');
var ReactDOM = require('react-dom');
import {Router, Route, IndexRoute, browserHistory} from 'react-router';

import App from './App';
import MainLayout from './components/MainLayout';
import Home from './components/home/Home';
import Product from './components/product/Product';
import Category from './components/category/Category';
import Cart from './components/cart/Cart';
import NotFound from './components/NotFound';

export default (
  <Router history={browserHistory}>
    <Route component={App} >
      <Route path='/' component={Home} />
      <Route path='/product/:productId' component={Product} />
      <Route path='/category/:catNumber' component={Category} />
      <Route path='/cart' component={Cart} />
    </Route>
    <Route path='*' component={NotFound} />
  </Router>
)

Now, I have three major problems, which makes me think that maybe I'm just terribly misunderstanding how the router works.现在,我遇到了三个主要问题,这让我觉得也许我只是对路由器的工作原理有很大的误解。

1) Strange url hashes from react [ http://localhost:3002/#/?_k=xv1opy] , even though they shouldn't be there, as I've already set history={browserHistory} 1) 来自 react [ http://localhost:3002/#/?_k=xv1opy] 的奇怪 url 哈希,即使它们不应该在那里,因为我已经设置了 history={browserHistory}

2) Browser console warnings: "Warning: Location "/" did not match any routes" and "Warning: You cannot change ; it will be ignored." 2) 浏览器控制台警告:“警告:位置“/”与任何路由不匹配”和“警告:您无法更改;它将被忽略。” Not sure what's happening here, as I've very clearly defined the Home component to render for path='/'.不确定这里发生了什么,因为我已经非常清楚地定义了要为 path='/' 呈现的 Home 组件。

3) Probably related, but any time I change routes, the entire application reloads, clearing all my store data. 3)可能相关,但每当我改变路线时,整个应用程序都会重新加载,清除我所有的商店数据。 Not ideal, but I think this can be fixed once I fix #1 and (especially) #2.不理想,但我认为这可以在我修复 #1 和(尤其是)#2 后修复。

More information that might be useful:更多可能有用的信息:

// app.js render() method // app.js render() 方法

render() {
return (
  <div>
    <Header />
    <Subheader />
    {this.props.children}
    <Footer />
  </div>
);

} }

// index.js // index.js

'use strict';

import React from 'react';
import ReactDOM from 'react-dom';

import Routes from './routes';

if ( process.env.NODE_ENV !== 'production') {
  window.React = React;
}

ReactDOM.render(Routes, document.getElementById('main'));

Anyone a bit more familiar with React who can point me in the right direction here?任何对 React 更熟悉的人可以在这里为我指出正确的方向吗? Been pulling my hair out for the past two days on this, and have read seemingly every guide on react-router to no avail.过去两天一直在为此拉我的头发,并且阅读了几乎所有关于 react-router 的指南都无济于事。

Your routing is a bit flawed.你的路由有点问题。 Try this instead:试试这个:

<Router history={browserHistory}>
  <Route path='/' component={App} >
    <IndexRoute component={Home} />
    <Route path='product/:productId' component={Product} />
    <Route path='category/:catNumber' component={Category} />
    <Route path='cart' component={Cart} />
  </Route>
  <Route path='*' component={NotFound} />
</Router>

This should solve most, if not all, of your errors.这应该可以解决大部分(如果不是全部)错误。

The Routing can be done easily type "localhost:3000/" type we can get the login page and if only get by creating a login page and other pages component路由可以很容易地完成输入“localhost:3000/”类型我们可以得到登录页面,如果只是通过创建登录页面和其他页面组件来获取

        import React from 'react';
        import { Component } from "react";
        import { BrowserRouter, Switch, Route } from 'react-router-dom';
        import "bootstrap/dist/css/bootstrap.min.css";
        import login from './components/loginpage-component';
        import signup from './components/signup-component';
        render(){
        return (
         <BrowserRouter>
             <Switch>
                <Route exact path="/" component={login} /> 
                <Route exact path="/signup" component={signup} /> 
                <Route exact path="/live" component={live}/>
             </Switch>  
         </BrowserRouter>
         );
        }

        }
       export default App;
  1. install react-router-dom using yarn or npm使用yarnnpm安装react-router-dom

    yarn add react-router-dom

  2. import react-router like this像这样导入反应路由器

    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

  3. Use it like this像这样使用它

    <Switch> <Route path="/scopes"> <Scopes /> </Route> <Route path={"/disciplines"}> <Disciplines /> </Route> <Route path={"/fields"}> <Fields /> </Route> <Route path={"/issues"}> <Issues /> </Route> <Route path={"/articles"}> <Articles /> </Route> <Route path={"/indexing"}> <Indexing /> </Route> <Route path={"/settings"}> <Settings /> </Route> </Switch>

  4. now you can create a link to each router like this现在您可以像这样创建到每个路由器的链接

    <Link to="/articles">Articles</Link>

    import Link as: import { Link } from 'react-router-dom' import Link as: import { Link } from 'react-router-dom'

If you follow this docs https://reactrouter.com/web/guides/quick-start , It says如果你按照这个文档https://reactrouter.com/web/guides/quick-start ,它说

Step 1: Move to the project folder and type npm install react-router-dom --save第 1 步:移至项目文件夹并键入 npm install react-router-dom --save

Step 2: import the route files第二步:导入路由文件

App.js应用程序.js

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

import Home from './components/home/Home';
import Product from './components/product/Product';
import Category from './components/category/Category';
import Cart from './components/cart/Cart';

const App = () => {
 return (
  <div>

   <Router>
    <Switch>

      <Route exact path="/">
        <Home />
      </Route>
      //by providing exact attribute will only match if the path matches the exact location else if we don't provide it will never render other components because it renders the first one that matches the current URL 
      <Route path="/product">
       <Product />
      </Route>
      <Route path="/category">
       <Category />
      </Route>
      <Route path="/cart">
       <Cart />
      </Route>
    </Switch>
   </Router>

 </div>
)
}
export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM