我正在调用ajax请求this.props.getPostListData(this.props.lang)
并收到错误。然后我发现它是componentDidMount的责任
我的componentDidMount
未在News.jsx
组件中调用,当我将其替换为componentWillMount
时,将调用ajax请求。
我使用 Redux 和 React Router v4
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);
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);
答案 0 :(得分:2)
如果我替换NewsCards
组件:
<NewsCards posts={postList} urlPrefix={urlPrefix} />
到
<pre><code>{JSON.stringify(postList)}</code></pre>
一切正常。所以问题出在 NewsCards 组件中。我需要更精确地检查它。