Webpack 2使用服务器端渲染和React-Router-v4进行代码分割

5

在使用webpack2.2.0-rc1和react routerv4时,可以使用这个代码片段来实现代码分割。其中提到:

function asyncComponent(getComponent) {
  return class AsyncComponent extends React.Component {
    static Component = null;
    state = { Component: AsyncComponent.Component };

    componentWillMount() {
      if (!this.state.Component) {
        getComponent().then(Component => {
          AsyncComponent.Component = Component
          this.setState({ Component })
        })
      }
    }
    render() {
      const { Component } = this.state
      if (Component) {
        return <Component {...this.props} />
      }
      return null
    }
  }
}

const Foo = asyncComponent(() =>
  System.import('./Foo').then(module => module.default)
)

它实际上是可行的,但我正在使用服务器端渲染。因此,在服务器上,我要求组件A,然后在客户端上System.import组件A。 最终,当我访问懒加载路由时,我会收到此React重用标记警告,因为客户端渲染最初从https://gist.github.com/acdlite/a68433004f9d6b4cbc83b5cc3990c194#file-app-js-L21中加载null组件A. 警告:React尝试在容器中重用标记,但校验和无效。这通常意味着您正在使用服务器渲染,并且服务器上生成的标记不是客户端期望的。React注入了新的标记来弥补这个问题,但您已经失去了许多服务器渲染的好处。相反,请找出为什么在客户端或服务器上生成的标记不同: (客户端)CO 0.0.0 </h1></div><!-- react-empty: 6 - (服务器)CO 0.0.0 </h1> </div><div data-radium="tru 如何避免这些错误?
1个回答

0

我刚刚在AsyncComponent中更改了line,使其在代码分割的组件尚未加载时返回一个brake标记
。然后,我不再需要在服务器端渲染实际组件,而是只需抛出另一个brake标记,这样标记实际上就匹配了。

这远非理想

export function Shell(Component) {
    return React.createClass({
        render: function () {
            return (
                <div>
                    <Bar/>
                    <Component {...this.props}/>
                </div>
            );
        }
    });
};

export const Waiting = React.createClass({
    render: function () {
        return (
            <div>
                <Bar/>
                <br/>
            </div>
        );
    }
});


// Client routes
const AsyncDash = Utils.asyncRoute(() => System.import("../components/dashboard/dashboard.tsx"));
const AsyncLogin = Utils.asyncRoute(() => System.import("../components/login/login"));

const routes = () => {
    return (<div>
            <Match exactly pattern="/" component={Shell(AsyncLogin)}/>
            <Match exactly pattern="/dashboard" component={Shell(AsyncDash)}/>
        </div>
    );
};


// Server routes
const routes = () => {
    return (<div>
            <Match exactly pattern="/" component={Waiting}/>
            <Match exactly pattern="/dashboard" component={Waiting}/>
        </div>
    );
};

你有没有遇到过这个问题的解决方案? - Nat Homer
2
很多解决方案。React-async-component是一种老的技巧,不要用。React-loadable是一种新的技巧。React-universal-component则更好,是一种最新的技巧。 - CESCO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接