ReactJS:如何在同一网站上拥有多个SPA

时间:2016-09-04 06:42:24

标签: javascript reactjs components single-page-application

我正在创建一个Airbnb克隆。

我注意到如果我将整个网站设为一个SPA,那么我的嵌套路线将是一个巨大的混乱。我想让每个标签都成为自己的SPA,但在尝试创建多个SPA时遇到了错误。

我所做的是创建一个App组件,然后将其呈现给Index.html,这有效!

但是当我创建了一个BecomeAHost组件,并试图将其渲染为BecomeAHost.html(另一个页面)时,我收到了一个错误:

bundle.js:886 Uncaught Invariant Violation: _registerComponent(...):
Target container is not a DOM element.

我的主要问题是:我如何在同一个网站上拥有多个ReactJS单页面应用程序,所以我没有大约30条路由全部嵌套在一起?

这是Github回购:https://github.com/strangebnb/template

这是我尝试在BecomeAHost.html

上呈现的第二个组件
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom';
import {Component} from 'react';
import { Router, Route, Link, IndexRoute, hashHistory, DefaultRoute, IndexLink, browserHistory } from 'react-router'

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton';
import ActionFavorite from 'material-ui/svg-icons/action/favorite';
import ActionFavoriteBorder from 'material-ui/svg-icons/action/favorite-border';

const styles = {
  block: {
    maxWidth: 250,
  },
  radioButton: {
    marginBottom: 16,
  },
};


const BecomeAHost = React.createClass ({
  render() {
    return(
      <MuiThemeProvider>
        <div>
          <First/>
        </div>
      </MuiThemeProvider>
    )
  }
})

const First = () => (
  <div>
    <h1>Become an Airbnb host</h1>
    <p>Start off by creating a listing page. Think of it as a profile page for your place.</p>
    <br></br>
    <p>Step 1</p>
    <h3>Start with the basics</h3>
    <h4>Beds, bathrooms, amenities, and more</h4>
  </div>
)

ReactDOM.render(<BecomeAHost />, document.getElementById('host'));

以下是我试图在页面上呈现它的方式

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Template</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
  </head>
  <body>
    <div id='host'>Loading...</div>
    <script src='./bundle/bundle.js' type="text/javascript"></script>
  </body>
</html>

我认为错误可能是我的webpack配置为仅处理我的主应用程序(我的主要应用程序在Index.html上工作)。这是我的webpack

var webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: {
        main: "./src/App.js"
    },
    output: {
        path: "./public",
        filename: "/bundle/bundle.js"
    },
    devtools: "sourcemap",
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: "babel"
            },
      {
        test: /\.scss$/,
        loaders:  ["style", "css", "sass"],
        exclude: /node_modules/
      }
        ]
    }

1 个答案:

答案 0 :(得分:3)

这是因为您的两个网页都加载了相同的捆绑包,它永远不会找到app host DOM元素来正确呈现。尝试使用webpack的multiple entry points,然后在每个.html中单独要求它们:

{
    entry: {
        a: "./a",
        b: "./b",
        c: ["./c", "./d"]
    },
    output: {
        path: path.join(__dirname, "dist"),
        filename: "[name].entry.js"
    }
}