首页 > 解决方案 > React 通用组件在连接到 store 时抛出错误

问题描述

尝试访问时发生错误/article/post...。这是 Routes.js 的代码片段,据说错误发生的地方。完整的错误堆栈跟踪位于https://pastebin.com/M0pCULPj完整的存储库位于https://github.com/ElAnonimo/webpack4_2。Article.js 缺少什么来正确渲染?

路线.js

import React from 'react';
import { Route, Link } from 'react-router-dom';
import { Switch } from 'react-router';
import universal from 'react-universal-component';
import NotFound from './NotFound';

const UniversalComponent = universal(props => import(`./${props.page}`));

export default () => <div>
  <div className="nav">
    <Link to='/about'>About</Link>
    <Link to='/'>Gallery</Link>
    <Link to='/article/post'>Article 1</Link>
    <Link to='/article/post2'>Article 2</Link>
  </div>
  <Switch>
    <Route path='/about' render={({ staticContext }) => {
      const site = staticContext ? staticContext.site : location.hostname.split('.')[0];
      return <UniversalComponent page='About' site={site} />}}
    />
    <Route exact path='/'>
      <UniversalComponent page='Gallery' />
    </Route>
    <Route path='/article/:slug' render={({ staticContext, match }) => {
      const site = staticContext ? staticContext.site : location.hostname.split('.')[0];
      return <UniversalComponent page='Article' site={site} match={match} />}}
    />
    <Route component={NotFound} />
  </Switch>
</div>

文章.js

import React from 'react';
import { connect } from 'react-redux';
import '../css/Article.scss';
import NotFound from './NotFound';
import { fetchArticle } from '../server/actions';

class Article extends React.Component {
  constructor() {
    super();
  }

  componentDidMount() {
    this.props.dispatch(fetchArticle(this.props.site, this.props.match.params.slug));
  }

  render() {
    const siteConfig = require(`../../data/${this.props.site}/siteConfig`);
    try {
      const imagePath = require(`../images/${siteConfig.aboutImage}`);
      require(`../css/${this.props.site}/theme.scss`);

      return (
        <div className='article'>
          <h1>{ this.props.title }</h1>
          <div className="content" dangerouslySetInnerHTML={{__html: this.props.__content}} />
        </div>
      );
    } catch(ex) {
      return <NotFound />
    }
  }
}

export default connect((state) => ({
  title: state.text,
  __content: state.content
}))(Article);

标签: code-splittingserver-side-renderingreact-universalcode-splitting-async

解决方案


推荐阅读