Javascript 如何使用反应创建多页面应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41956465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create multiple page app using react
提问by StreetCoder
I have created a single page web app using react js. I have used webpackto create bundle of all components. But now I want to create many other pages. Most of pages are API call related. i.e. in the index.html, I have displayed content from API. I want to insert content in another page parsing data from API. Webpack compresses everything of react in a file which is bundle.js. However, the configuration of webpackis as follow:
我使用 react js 创建了一个单页 Web 应用程序。我曾经webpack创建过所有组件的包。但现在我想创建许多其他页面。大多数页面都与 API 调用相关。即在 中index.html,我已显示来自API. 我想在另一个页面中插入内容,解析来自 API 的数据。Webpack 将 react 的所有内容压缩到一个 .react 文件中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;
Now, I am confused what kind of configuration of webpackwill be for other page or what is the correct way to build multi-pages app using react.js
现在,我很困惑webpack其他页面的配置类型或使用构建多页面应用程序的正确方法是什么react.js
回答by nbkhope
(Make sure to install react-router using npm!)
(确保使用 npm 安装 react-router!)
To use react-router, you do the following:
要使用 react-router,请执行以下操作:
Create a file with routesdefined using Route, IndexRoute components
Inject the Router(with 'r'!) component as the top-level component for your app, passing the routes defined in the routes file and a type of history (hashHistory, browserHistory)
- Add {this.props.children}to make sure new pages will be rendered there
- Use the Linkcomponent to change pages
创建一个文件路径使用路线,IndexRoute组件定义
注入路由器(带有'r'!)组件作为应用程序的顶级组件,传递路由文件中定义的路由和一种历史类型(hashHistory、browserHistory)
- 添加{this.props.children}以确保新页面将在那里呈现
- 使用链接组件更改页面
Step 1routes.js
步骤 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 (
<Route path="/" component={App}>
<IndexRoute component={MainPage} />
<Route path="/some/where" component={SomePage} />
<Route path="/some/otherpage" component={SomeOtherPage} />
</Route>
);
Step 2entry point (where you do your DOM injection)
第 2 步入口点(您进行 DOM 注入的地方)
// You can choose your kind of history here (e.g. browserHistory)
import { Router, hashHistory as history } from 'react-router';
// Your routes.js file
import routes from './routes';
ReactDOM.render(
<Router routes={routes} history={history} />,
document.getElementById('your-app')
);
Step 3The App component(props.children)
Step 3 App 组件(props.children)
In the render for your App component, add {this.props.children}:
在 App 组件的渲染中,添加 {this.props.children}:
render() {
return (
<div>
<header>
This is my website!
</header>
<main>
{this.props.children}
</main>
<footer>
Your copyright message
</footer>
</div>
);
}
Step 4Use Link for navigation
步骤 4使用链接进行导航
Anywhere in your component render function's return JSX value, use the Link component:
在组件渲染函数的返回 JSX 值中的任何地方,使用 Link 组件:
import { Link } from 'react-router';
(...)
<Link to="/some/where">Click me</Link>
回答by Lucas Andrade
Preface
前言
This answer uses the dynamic routingapproach embraced in react-routerv4+. Other answersmay reference the previously-used "static routing" approach that has been abandonedby react-router.
此答案使用v4+ 中包含的动态路由方法react-router。其他答案可以参考已经被先前使用的“静态路由”的方式放弃了通过react-router。
Solution
解决方案
react-routeris a great solution. You create your pages as Components and the router swaps out the pages according to the current URL. In other words, it replaces your original page with your new page dynamically instead of asking the server for a new page.
react-router是一个很好的解决方案。您将页面创建为组件,路由器会根据当前 URL 换出页面。换句话说,它会动态地用新页面替换您的原始页面,而不是向服务器请求新页面。
For web apps I recommend you read these two things first:
对于网络应用程序,我建议您先阅读以下两件事:
- Full Tutorial
- The react-router docs; it will help you get a better understanding of how Router works.
Summary of the general approach:
一般方法总结:
1 -Add react-router-domto your project:
1 -添加react-router-dom到您的项目:
Yarn
纱
yarn add react-router-dom
or NPM
或NPM
npm install react-router-dom
2 -Update your index.jsfile to something like:
2 -将您的index.js文件更新为:
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render((
<BrowserRouter>
<App /> {/* The various pages will be displayed by the `Main` component. */}
</BrowserRouter>
), document.getElementById('root')
);
3 -Create a Maincomponent that will show your pages according to the current URL:
3 -创建一个Main组件,将根据当前 URL 显示您的页面:
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from '../pages/Home';
import Signup from '../pages/Signup';
const Main = () => {
return (
<Switch> {/* The Switch decides which component to show based on the current URL.*/}
<Route exact path='/' component={Home}></Route>
<Route exact path='/signup' component={Signup}></Route>
</Switch>
);
}
export default Main;
4 -Add the Maincomponent inside of the App.jsfile:
4 -Main在App.js文件中添加组件:
function App() {
return (
<div className="App">
<Navbar />
<Main />
</div>
);
}
5 -Add Links to your pages.
5 -将Links添加到您的页面。
(You must use Linkfrom react-router-dominstead of just a plain old <a>in order for the router to work properly.)
(为了让路由器正常工作,您必须使用Linkfromreact-router-dom而不是普通的旧的<a>。)
import { Link } from "react-router-dom";
...
<Link to="/signup">
<button variant="outlined">
Sign up
</button>
</Link>
回答by Taylor Jones
This is a broad question and there are multiple ways you can achieve this. In my experience, I've seen a lot of single page applications having an entry point file such as index.js. This file would be responsible for 'bootstrapping' the application and will be your entry point for webpack.
这是一个广泛的问题,有多种方法可以实现这一点。根据我的经验,我见过很多单页应用程序都有一个入口点文件,例如index.js. 该文件将负责“引导”应用程序,并将成为 webpack 的入口点。
index.js
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Application from './components/Application';
const root = document.getElementById('someElementIdHere');
ReactDOM.render(
<Application />,
root,
);
Your <Application />component would contain the next pieces of your app. You've stated you want different pages and that leads me to believe you're using some sort of routing. That could be included into this component along with any libraries that need to be invoked on application start. react-router, redux, redux-saga, react-devtoolscome to mind. This way, you'll only need to add a single entry point into your webpack configuration and everything will trickle down in a sense.
您的<Application />组件将包含您的应用程序的下一部分。你已经声明你想要不同的页面,这让我相信你正在使用某种路由。这可以与需要在应用程序启动时调用的任何库一起包含在此组件中。react-router, redux, redux-saga,react-devtools想到。这样,你只需要在你的 webpack 配置中添加一个入口点,一切都会在某种意义上滴落下来。
When you've setup a router, you'll have options to set a component to a specific matched route. If you had a URL of /about, you should create the route in whatever routing package you're using and create a component of About.jswith whatever information you need.
设置路由器后,您可以选择将组件设置为特定的匹配路由。如果您的 URL 为/about,则应该在您使用的任何路由包中创建路由,并使用About.js您需要的任何信息创建一个组件。

