【问题标题】:Rendering UI in React Router 4在 React Router 4 中渲染 UI
【发布时间】:2018-12-21 08:44:30
【问题描述】:

我对 ReactJS 还是很陌生,尤其是它的路由部分。我有几个问题,我尝试了在 stackoverflow 上找到的许多解决方案,但似乎没有任何帮助:

  1. 当我在本地启动我的 react 项目时,我得到localhost:3000。如果我希望它显示为 localhost:3000/extension/ 怎么办?

  2. 当我浏览我的项目时,我可以呈现不同的页面。但是,如果我直接在浏览器中输入 URL,则会呈现一个空白页面。没有错误。我在某处读到说我的组件没有连接到我的路线。我不确定我需要做什么来纠正它。

  3. 如何确保正确利用历史记录?

routes.js:

const RouteList = () => (
<Switch>
  <Route path="/extension/" exact component={withRouter(HomePage)} />
  <Route path="/extension/something" exact component={withRouter(SomethingPage)} />
  <Route component={Error} />
</Switch>

);

App.js:

class  App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render () {
    return (
      <Router history={browserHistory}>
        <div>
          <Header />
          <RouteList />
          <Footer />
        </div>
      </Router>
    );
  }
}

export default App;

--编辑-- 添加了我的 webpack.config.js

const commonConfig = {

  resolve: {
    modules: [path.resolve('./src'), 'node_modules'],
    extensions: ['.js', '.csv', '.json', '.scss', '.css', '.html']
  },


  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        enforce: 'pre',
        use: [{ loader: 'eslint-loader', options: { configFile: '.eslintrc' } }]
      },
      {
        use: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      },
      {
        test: /\.html$/,
        use: [{ loader: 'htmlhint-loader', options: { configFile:     '.htmlhintrc' } }],
        exclude: /node_modules/,
        enforce: 'pre'
      },
      {
        test: /\.(png|jpg|jpeg|svg|gif|svg|woff|woff2|ttf|eot)(\?    v=\d+\.\d+\.\d+)?$/,
        use: 'file-loader'
      },
      {
        use: [{
          loader: 'html-loader'
        }],
        test: /\.html$/
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(nodeEnv)
       }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module) {
        if (module.resource && (/^.*\. 
   (css|less|scss)$/).test(module.resource)) {
          return false;
        }
        return module.context && module.context.indexOf('node_modules') !== -1;
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    new CopyWebpackPlugin([{
      from: __dirname + '/src/images',
      to: ''
    }]),
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: 'dependency'
    }),
    new webpack.optimize.ModuleConcatenationPlugin()
  ]
};


const devConfig = {
  entry: {
    main: ['whatwg-fetch', 'core-js/es6', 'react-hot-loader/patch', 'index.js',
      'webpack-hot-middleware/client?reload=true']
  },

  target: 'web',

  devtool: 'inline-source-map',

  output: {
    path: path.join(__dirname, '/dev_build'),
    filename: '[name].bundle.js',
    publicPath: '/'
  },

  module: {
    rules: [
      {
        test: /\.scss/,
        include: path.resolve(__dirname, 'src/styles'),
        use: ['style-loader', 'css-loader', {loader: 'sass-loader', options: 
{sourceMap: true}}]
      },
      {
        test: /\.css$/,
        exclude: [/node_modules/],
        use: ['style-loader', 'css-loader?modules']
      },
      {
        test: /\.css$/,
        include: [/node_modules/],
        use: ['style-loader', 'css-loader']
      }
    ]
  },

 devServer: {
    contentBase: 'src',
    compress: true,
    hot: true,
    port: 3000,
    host: '0.0.0.0',
    disableHostCheck: true,
    historyApiFallback: {
      disableDotRule: true,
      index: 'build/index.html'
    },
    stats: 'minimal',
    overlay: true,
    proxy: {
      '/api/**': {
        target: {
          port: 8080
        },
        secure: false
      },
      '/actuator/**': {
        target: {
          port: 8080
        },
        secure: false
      },
    }
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  ]
};

请帮忙,因为我不确定我做错了什么,我为此绞尽脑汁。谢谢。

【问题讨论】:

  • 你使用 express 还是 webpack 开发服务器?
  • 我正在使用 webpack 开发服务器

标签: reactjs react-router-v4 browser-history


【解决方案1】:

如果您希望将其作为目标网页,可以将 Redirect/ 添加到 /extension

const RouteList = () => (
  <Switch>
    <Redirect from='/' to='/extension/'/>
    <Route path="/extension/" exact component={HomePage} />
    <Route path="/extension/something" exact component={SomethingPage} />
    <Route component={Error} />
  </Switch>
);

您的应用目前仅在访问 / 时才有效,因为您的服务器只会为索引路由提供 index.html。如果您希望提供 index.html 文件而不是任何 404 响应,则可以使用 historyApiFallback

webpack.config.js

module.exports = {
  //...
  devServer: {
    historyApiFallback: true
  }
};

【讨论】:

    猜你喜欢
    • 2018-02-11
    • 2019-02-09
    • 2017-12-20
    • 2020-12-18
    • 2016-02-22
    • 2019-01-02
    • 2016-06-13
    • 2023-02-06
    • 2023-03-08
    相关资源
    最近更新 更多