简体   繁体   English

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

[英]How to create multiple page app using react

I have created a single page web app using react js.我使用 react js 创建了一个单页 Web 应用程序。 I have used webpack to create bundle of all components.我已经使用webpack创建了所有组件的包。 But now I want to create many other pages.但现在我想创建许多其他页面。 Most of pages are API call related.大多数页面都与 API 调用相关。 ie in the index.html , I have displayed content from API .即在index.html ,我显示了来自API内容。 I want to insert content in another page parsing data from API.我想在另一个页面中插入内容,解析来自 API 的数据。 Webpack compresses everything of react in a file which is bundle.js . Webpack 将 react 的所有内容压缩到一个文件bundle.js However, the configuration of webpack is as follow:但是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 webpack will be for other page or what is the correct way to build multi-pages app using react.js现在,我很困惑其他页面的webpack配置是什么样的,或者使用react.js构建多页面应用程序的正确方法是什么

(Make sure to install react-router using npm!) (确保使用 npm 安装 react-router!)

To use react-router, you do the following:要使用 react-router,请执行以下操作:

  1. Create a file with routes defined using Route, IndexRoute components创建使用路线,IndexRoute组件与定义的路由文件

  2. 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)注入路由器(带有'r'!)组件作为应用程序的顶级组件,传递路由文件中定义的路由和一种历史类型(hashHistory、browserHistory)

  3. Add {this.props.children} to make sure new pages will be rendered there添加{this.props.children}以确保新页面将在那里呈现
  4. Use the Link component to change pages使用链接组件更改页面

Step 1 routes.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 2 entry 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 3 The 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 4 Use 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>

Preface前言

This answer uses the dynamic routing approach embraced in react-router v4+.此答案使用react-router v4+ 中包含的动态路由方法。 Other answers may reference the previously-used "static routing" approach that has been abandoned by react-router .其他答案可能会参考以前使用的“静态路由”方法,该方法已被react-router放弃

Solution解决方案

react-router is a great solution. react-router是一个很好的解决方案。 You create your pages as Components and the router swaps out the pages according to the current URL.您将页面创建为组件,路由器会根据当前 URL 换出页面。 In other words, it replaces your original page with your new page dynamically instead of asking the server for a new page.换句话说,它会动态地用新页面替换您的原始页面,而不是向服务器请求新页面。

For web apps I recommend you read these two things first:对于网络应用程序,我建议您先阅读以下两件事:

Summary of the general approach:一般方法总结:

1 - Add react-router-dom to your project: 1 -react-router-dom添加到您的项目中:

Yarn

yarn add react-router-dom

or NPMNPM

npm install react-router-dom

2 - Update your index.js file 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 Main component 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 Main component inside of the App.js file: 4 -App.js文件中添加Main组件:

function App() {
  return (
    <div className="App">
      <Navbar />
      <Main />
    </div>
  );
}

5 - Add Link s to your pages. 5 -Link添加到您的页面。

(You must use Link from react-router-dom instead of just a plain old <a> in order for the router to work properly.) (您必须使用react-router-dom Link而不是简单的旧<a>才能使路由器正常工作。)

import { Link } from "react-router-dom";
...
<Link to="/signup">
  <button variant="outlined">
    Sign up
  </button>
</Link>

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 .根据我的经验,我见过很多单页应用程序都有一个入口点文件,比如index.js This file would be responsible for 'bootstrapping' the application and will be your entry point for webpack.该文件将负责“引导”应用程序,并将成为 webpack 的入口点。

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.您的<Application />组件将包含您的应用程序的下一部分。 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-devtools come to mind.想到react-routerreduxredux-sagareact-devtools This way, you'll only need to add a single entry point into your webpack configuration and everything will trickle down in a sense.这样,你只需要在你的 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.js with whatever information you need.如果你有一个/about的 URL,你应该在你使用的任何路由包中创建路由,并使用你需要的任何信息创建一个About.js组件。

The second part of your question is answered well.你问题的第二部分回答得很好。 Here is the answer for the first part: How to output multiple files with webpack:这是第一部分的答案:如何使用 webpack 输出多个文件:

    entry: {
            outputone: './source/fileone.jsx',
            outputtwo: './source/filetwo.jsx'
            },
    output: {
            path: path.resolve(__dirname, './wwwroot/js/dist'),
            filename: '[name].js'      
            },

This will generate 2 files: outputone.js und outputtwo.js in the target folder.这将在目标文件夹中生成 2 个文件:outputone.js 和 outputtwo.js。

还可以使用gatsby一个专用于静态多页应用程序的反应框架。

Following on from the answer above by @lucas-andrade : for react-router versions >= 6, Switch no longer exists (see https://github.com/remix-run/react-router/issues/8439 ).继@lucas-andrade 上面的回答之后:对于react-router版本 >= 6, Switch不再存在(参见https://github.com/remix-run/react-router/issues/8439 )。 The content of step 3 becomes:步骤3的内容变为:

import React from 'react';
import { Routes, Route } from 'react-router-dom';

import Home from '../pages/Home';
import Signup from '../pages/Signup';

const Main = () => {
  return (
    <Routes>
      <Route path='/' element={Home}></Route>
      <Route path='/signup' element={Signup}></Route>
    </Routes>
  );
}

export default Main;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM