react路由器在为url提供路径时忽略嵌套路由

react-router ignoring nested routes when providing url with path

本文关键字:嵌套 路由 路径 路由器 url react      更新时间:2024-03-23

我在玩reactredux,试图用react-routes构建一个基本的应用程序。目前,我已经成功地将以下内容放在一起,这些内容适用于WrapperHome页面,但如果我转到localhost:8080/apps,"应用程序"页面似乎无法加载。我每次只得到404分。

你知道我在哪里出了问题吗?

控制台中没有错误或警告,我试着在网上查看了几个例子,但似乎没有一个与我的特别不同

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import Routes from './routes/routes';
import { configureStore } from './store/configureStore';
const rootElem = document.getElementById('mount');
const store = configureStore(browserHistory);
const history = syncHistoryWithStore(browserHistory, store);
const provider = <Provider store={store}><Routes history={history} /></Provider>;
ReactDOM.render(provider, rootElem);

routes/routes.js

import React from 'react';
import { Router, Route, IndexRoute } from 'react-router'
import { Wrapper, Home, Apps } from './../views';
class Routes extends React.Component {
    render () {
        const { history } = this.props;
        return(
            <Router history={history}>
                <Route path='/' component={Wrapper}>
                    <IndexRoute component={Home}/>
                    <Route path='apps' component={Apps}/>
                </Route>
            </Router>
        );
    }
}
Routes.propTypes = {
    history: React.PropTypes.object.isRequired
};
export default Routes;

store/configureStore.js

import { createStore, applyMiddleware, compose } from 'redux';
import { routerMiddleware } from 'react-router-redux'
import createLogger from "redux-logger";
import thunk from 'redux-thunk';
import rootReducer from './../reducers'
export function configureStore(history, initialState = {}) {
    const logger = createLogger();
    const middleware = routerMiddleware(history);
    const store = createStore(
        rootReducer,
        initialState,
        compose(
            applyMiddleware(thunk, middleware, logger),
            window.devToolsExtension ? window.devToolsExtension() : f => f
        )
    );
    return store;
}

减速器/index.js

import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
export default combineReducers({
    //...reducers,
    routing: routerReducer
});

您使用的是react路由器中的browserHistory,因此您的服务器需要能够处理深度链接并仍然提供正确的文件。由于您正在连接到8080端口,我认为您可能正在使用webpack-dev服务器。

您可以切换到hashHistory,一切都会正常工作。react router文档解释了设置服务器以使用browserHistory:https://github.com/reactjs/react-router/blob/master/docs/guides/Histories.md

对于webpack-dev服务器,您只需要在配置对象中传递一个额外的选项:historyApiFallback: true。这将使开发服务器使用连接历史api回退返回任何深度链接请求的index.html。

...
devServer: {
  historyApiFallback: true
}
...