gpt4 book ai didi

javascript - 无法获取/使用 React Router

转载 作者:行者123 更新时间:2023-11-28 14:56:20 25 4
gpt4 key购买 nike

我有 2 个文件 jsx:

当我访问localhost:8080时是正常的。但是当我访问 localhost:8080/home 时,浏览器中显示消息 Cannot GET/home

我该如何解决?

Home.jsx:

import React from 'react';


class Home extends React.Component{

constructor(props) {
super(props);

}

render(){

return(
<div>
<h1>Home ...</h1>
</div>

)
}
}
export default Home;

index.jsx:

import React from 'react';
import {render} from 'react-dom';
import Home from './Home.jsx';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router';



class App extends React.Component {

render(){
return(
<div>
<ul>
<li>Home</li>
</ul>
{this.props.children}
</div>
);
}


}

render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />

</Route>
</Router>

), document.getElementById('app'));

文件 webpack.config.js:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');

var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
devServer: {
inline: true,
port: 8080,
contentBase: "./src/client",

hot: true
},
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
};

module.exports = config;

最佳答案

在您的 devServer 配置中,您需要 historyApiFallback 设置:

   devServer: {
inline: true,
port: 8080,
contentBase: "./src/client",
historyApiFallback: true,
hot: true
},

这告诉devServer始终返回根html页面并让客户端进行路由。换句话说,回退到根 API 路由。

关于javascript - 无法获取/使用 React Router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42666569/

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