如何使用react创建多个页面应用程序

我使用react js创建了一个单页Web应用程序。 我使用webpack来创建所有组件的捆绑。 但现在我想创建许多其他页面。 大多数页面都与API调用相关。 即在index.html ,我显示了API内容。 我想在另一个页面中插入内容,从API中解析数据。 Webpack压缩文件中的所有响应,即bundle.js 。 但是, webpack的配置如下:

 const webpack = require('webpack'); var config = { entry: './main.js', output: { path:'./', filename: 'dist/bundle.js', }, devServer: { inline: true, port: 3000 }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ] } module.exports = config; 

现在,我很困惑webpack将用于其他页面的配置是什么样的,或者使用react.js构建多页面应用程序的正确方法是什么

(确保使用npm安装react-router!)

要使用react-router,请执行以下操作:

  1. 使用Route,IndexRoute组件创建包含路由的文件

  2. 注入路由器 (带’r’!)组件作为应用程序的顶级组件,传递routes文件中定义的路由和一种历史记录(hashHistory,browserHistory)

  3. 添加{this.props.children}以确保在那里呈现新页面
  4. 使用“ 链接”组件更改页面

第1步 routes.js

 import React from 'react'; import { Route, IndexRoute } from 'react-router'; /** * Import all page components here */ import App from './components/App'; import MainPage from './components/MainPage'; import SomePage from './components/SomePage'; import SomeOtherPage from './components/SomeOtherPage'; /** * All routes go here. * Don't forget to import the components above after adding new route. */ export default (      ); 

第2步入口 点(进行DOM注入的地方)

 // You can choose your kind of history here (eg browserHistory) import { Router, hashHistory as history } from 'react-router'; // Your routes.js file import routes from './routes'; ReactDOM.render( , document.getElementById('your-app') ); 

第3步 App组件 (props.children)

在App组件的渲染中,添加{this.props.children}:

 render() { return ( 
This is my website!
{this.props.children}
Your copyright message
); }

步骤4 使用链接进行导航

组件中的任何位置渲染函数返回JSX值,使用Link组件:

 import { Link } from 'react-router'; (...) Click me 

这是一个广泛的问题,您可以通过多种方式实现这一目标。 根据我的经验,我看过很多单页应用程序都有一个入口点文件,比如index.js 。 该文件将负责“引导”应用程序,并将成为webpack的入口点。

index.js

 import React from 'react'; import ReactDOM from 'react-dom'; import Application from './components/Application'; const root = document.getElementById('someElementIdHere'); ReactDOM.render( , root, ); 

您的组件将包含您的应用程序的下一部分。 你已经说过你想要不同的页面,这让我相信你正在使用某种路由。 这可以包含在此组件中,以及需要在应用程序启动时调用的任何库。 我想到了react-routerreduxredux-sagareact-devtools 。 这样,您只需要在webpack配置中添加一个入口点,从某种意义上说,一切都会崩溃。

设置路由器后,您可以选择将组件设置为特定的匹配路由。 如果您的URL为/about ,则应在您正在使用的任何路由包中创建路由,并使用您需要的任何信息创建About.js的组件。