繁体   English   中英

React-Router嵌套路由不起作用

[英]React-Router Nested Routes not working

重现步骤

client.js(入口文件)

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, browserHistory } from 'react-router';
import reduxThunk from 'redux-thunk';

import reducers from './reducers';
import routes from './routes.js';

const storeWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = storeWithMiddleware(reducers);

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>, document.getElementById('app')
);

routes.js(版本1)

import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './components/bases/app.js';
import Login from './components/app/authentication/login.js';

export default(
  <Route path="/" component={App}>
    <Route path="signup" component={Login}/>
  </Route>
)

routes.js(版本2)

let routes = {
  path: '/',
  component: App,
  childRoutes: [
    { path: 'signup', component: Login }
  ]
}

export default routes;

预期行为

期望有/signup路由可用。

实际行为

react-router找不到路由/signup但可以找到/

看一下chrome dev-tools的source-tab,我发现:

当看“ /”

sources
--------
dist/prod
|     bundle.js
index.html

在查看“ / signup”时

sources
--------
signup

如果您更改为hashHistory并成功,则可能是您的后端,它可以提供html ...

由于hashHistory的工作方式如下:

example.com/#/signup

浏览器不理解为新的GET,如果您使用browserHistory,则这是:

example.com/signup

再次向浏览器发出index.html请求,但在路径/ signup上...但是webpack开发服务器可能不理解。。尝试添加historyApiFallback:true到webpack配置中

https://github.com/amacneil/react-router-webpack-history-example

赠品是当您查看来源时正在提供的文件。 当您尝试加载/signup页面时,您的浏览器正在尝试加载signup页面。

使用browserHistory ,需要为所有可能的路线提供index.html (及其中包括的所有脚本)。 这意味着您需要有一台接受所有可能路由并做出相应响应的服务器。

例如,如果要使用express运行节点服务器,则需要一个通配符路由处理程序:

// define static handler first for .js, etc.
app.use(express.static(path.join(__dirname, 'public')));

// all other routes should server your index.html file
app.get("/", handleRender);
app.get("*", handleRender);

function handleRender(req, res){
  res.sendFile(__dirname + '/index.html');
}

暂无
暂无

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

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