gpt4 book ai didi

javascript - React Router 总是显示 IndexRoute

转载 作者:行者123 更新时间:2023-11-29 23:56:36 25 4
gpt4 key购买 nike

这是我的主要应用文件:

import React from 'react';
import { render } from 'react-dom';
import { browserHistory, Router, Route, IndexRoute } from 'react-router';

// Components
import Main from './components/core/Main.component';
import NotFound from './components/core/NotFound.component';
import About from './components/About.component';
import TeaTimer from './components/TeaTimer.component';

// App css
require('style!css!sass!applicationStyles');

render(
(<div>
<Router history={browserHistory}>
<Route component={Main} path="/">
<IndexRoute component={TeaTimer} />
<Route component={About} path="/about"/>
</Route>
<Route component={NotFound} path="*"/>
</Router>
</div>),
document.querySelector('#app')
);

这是我的主要组件:

import React, { Component } from 'react';

class Main extends Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}

Main.propTypes = {
children: React.PropTypes.object
}

export default Main;

这是我的快速服务器设置:

var express = require('express');

// Create our app
var app = express();
const PORT = process.env.PORT || 3000;

app.use(function (req, res, next){
if (req.headers['x-forwarded-proto'] === 'https') {
res.redirect('http://' + req.hostname + req.url);
} else {
next();
}
});

app.use(express.static('public'));

app.listen(PORT, function () {
console.log('Express server is up on port ' + PORT);
});

现在,当我打开浏览器并转到 http://localhost:3000 时,我得到了 TeaTimer 组件。 http://localhost:3000/#/相同,http://localhost:3000/#/about相同,未定义路由相同 - http://localhost:3000/#/sdnaipwnda[j.

但是当我访问 http://localhost:3000/about 时,我得到:

Cannot GET /about

我做错了什么?

如果您需要更多信息,请询问,我会将其添加到问题中,或者查看此 git repo .

最佳答案

好的,这个很简单。您只是在使用错误的历史记录。你需要hashHistory如果你想要基于哈希的,即 /#/about等等,路线。


import {Router, hashHistory} from 'react-router'
...
<Router history={hashHistory}>
...

如果您不想要基于散列的历史记录,但更喜欢外观常规的 URL,例如 /about等等,那么你确实需要 browserHistory .但是,在这种情况下,您必须确保您的 Web 服务器服务于相同的 index.html对于所有类似路由的 URL。这在 react-router 中有解释。 ' documentation .您需要在 express 服务器的路由配置末尾添加类似这样的内容:


// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
上面的代码假定您的 index.html 文件位于 public/ ,因此您可能需要将参数更改为 path.resolve .

我实际上更喜欢只为没有扩展名的 URL 返回 index.html。这样一来,只要请求的资源丢失,您就可以防止将 index.html 用作 .png 或 .js,而是获得有意义的 404。


app.get('*', function (request, response){
if (request.path.match(/\/[^\/.]*$/)) {
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
}
})

关于javascript - React Router 总是显示 IndexRoute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41463995/

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