react-router 4不显示组件

时间:2017-09-21 20:52:02

标签: reactjs react-router react-redux react-router-v4 react-router-dom

我的react-redux app中有2条路线:

ReactDOM.render(

<Provider store={store}>
    <BrowserRouter>

        <div>
            <Route path = '/a' component = {ContainerComponent} />
            <Route path = '/b' component = {ContainerComponent} />
        </div>      

    </BrowserRouter>
</Provider>, 

document.getElementById('app'));

我的webpack配置:

var HTMLWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.html',
    inject: 'body'
});

module.exports = {
    entry:  __dirname + '/app/index.js',
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            }, {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader?modules,localIdentName="[name]-[local]-[hash:base64:6]"'
                })
            }]
    },
    output: {
        filename: 'transformed.js',
        path: __dirname + '/build'
    },
    devServer: {

        historyApiFallback: true

    },
    plugins: [
        HTMLWebpackPluginConfig,
        new ExtractTextPlugin('styles.css')
    ]
};

code

Result

2 个答案:

答案 0 :(得分:1)

ReactDOM.render(

<Provider store={store}>
    <BrowserRouter>

        <div>
            <Route path = '/a' component = {ContainerComponent} />
            <Route path = '/b' component = {ContainerComponent} />
            <Route path = '/a/b' component = {ContainerComponent} />

        </div>      

    </BrowserRouter>
</Provider>, 

document.getElementById('app'));

您还需要定义第三条路线。由于路径匹配的功能,在不使用exact参数的情况下,BrowserRouter将匹配路径与浏览的URL匹配的路由所定义的路由。在这种情况下,使用URL /a,您将获得两个呈现的组件。但是,如果您浏览URL /a/b,则唯一匹配路径的路径是第三个路径。因为您没有在代码中定义,所以会收到正确的404错误。

答案 1 :(得分:0)

好的,最后,通过修改 webpack.config.js 解决了这个问题。取而代之:

output: {
    filename: 'transformed.js',
    path: __dirname + '/build',
},

用这个:

output: {
    filename: 'transformed.js',
    path: __dirname + '/build',
    publicPath: '/'
},