componentDidMount未被调用

时间:2017-09-18 12:29:13

标签: javascript reactjs

我正在调用ajax请求this.props.getPostListData(this.props.lang)并收到错误。然后我发现它是componentDidMount的责任 我的componentDidMount未在News.jsx组件中调用,当我将其替换为componentWillMount时,将调用ajax请求。
我使用 Redux React Router v4

News.jsx

class News extends Component {
  componentDidMount() {
      this.props.getPostListData(this.props.lang);
  }

  props: {
    urlPrefix: string,
    lang: string,
    postList: PostListData,
    getPostListData: Function
  };

  render() {
    const { postList, urlPrefix } = this.props;
    return (
      <section className={'news'}>
        ...
        <NewsCards posts={postList} urlPrefix={urlPrefix} />
      </section>
    );
  }
}

const mapStateToProps = state => {
  const urlPrefix = getPrefix(state.locale);
  const postList = state.postlistData ? state.postlistData : [];
  const lang = getLang(state.locale);
  return { postList, lang, urlPrefix };
};

const mapDispatchToProps = (dispatch: Function) => ({
  getPostListData(locale) {
    dispatch(getPostList(locale));
  }
});

export default connect(mapStateToProps, mapDispatchToProps)(News);

Routes.jsx

const Routes = ({ urlPrefix }: { urlPrefix: string }) => (
  <BrowserRouter>
    <div className="app">
      <Route render={props => <Header urlPrefix={urlPrefix} {...props} />} />
      <Switch>
        <RootRouter exact
          path={'/:lang(en|ru)?'} urlPrefix={urlPrefix} component={Landing} />
        <Route exact path={'/:lang(en|ru)?/news'} component={News} />
        <Route component={FourOhFour} />
      </Switch>
      <Footer />
    </div>
  </BrowserRouter>
);

const mapStateToProps = state => ({ urlPrefix: getPrefix(state.locale) });    
export default connect(mapStateToProps)(Routes);

1 个答案:

答案 0 :(得分:2)

如果我替换NewsCards组件:

<NewsCards posts={postList} urlPrefix={urlPrefix} />

<pre><code>{JSON.stringify(postList)}</code></pre>

一切正常。所以问题出在 NewsCards 组件中。我需要更精确地检查它。