React Router v4 路由不起作用 [英] React Router v4 routes not working

查看:58
本文介绍了React Router v4 路由不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 React 比较陌生,我正在尝试弄清楚如何让 React 路由器工作.我有一个超级简单的测试应用程序,如下所示:

I am relatively new to reacts and I'm trying to figure out how to get React router to work. I've got a super simple test app that looks like this:

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

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

const Home = () => <h1><Link to= "/about">Click Me</Link></h1>
const About = () => <h1>About Us</h1>

const Test = () => (
  <Router>
    <Switch>
    <Route path ="/" component = {Home} />
    <Route path ="/about" component = {About} />
    </Switch>
  </Router>
)

ReactDOM.render(<Test />, document.getElementById('app'));

当我运行应用程序时,home 组件加载没有任何问题,当我单击单击我"链接时,url 更改为 localhost/about,但是没有任何反应.如果我单击刷新,我会收到无法 GET/about".显然我做错了什么,但我无法弄清楚是什么.我也在使用 Webpack.

when I run the app the home component loads without any trouble, and when I click the "Click Me" link the url changes to localhost/about, however nothing happens. If I click refresh I get a "Cannot GET /about." Clearly I am doing something wrong but I haven't been able to figure out what. I am also using Webpack.

推荐答案

/ 需要使用准确的路径,否则也会匹配 /about.

You need to use an exact path for / otherwise it will also match /about.

<Route exact path="/" component={Home} />

正如评论中提到的,对于这么简单的事情,我建议使用 Create React App 这将确保你的服务器代码和你的 webpack 设置都是正确的.使用 create-react-app 后,您只需要使用 npm 安装 react router v4 包,然后将上面的代码放入 App.js 文件,它应该可以工作.对您的代码进行了一些小的更改,以使其与 create-react-app 一起使用,如下所示:

As mentioned in the comments, for something this simple I would suggest using Create React App which will make sure your server code and your webpack settings are all correct. Once you use create-react-app you'll just need to use npm to install the react router v4 package, and then put your code above into the App.js file and it should work. There are some small changes to your code to get it to work with create-react-app as can be seen below:

// App.js
import React from 'react';

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

const Home = () => <h1><Link to="/about">Click Me</Link></h1>
const About = () => <h1>About Us</h1>

const App = () => (
  <Router>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </Switch>
  </Router>
)

export default App;

React Router V4 文档中的快速入门说明 会告诉你和我刚才解释的差不多.

The quick start instructions from React Router V4 documentation will tell you pretty much the same as I just explained.

这篇关于React Router v4 路由不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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