我一直在尝试使用Reacts组件功能制作组件。在这种情况下,我对componentDidMount特别感兴趣。
然而,无论我尝试什么,我的状态都不会传播到组件。
以下是组件:
class MainPage extends React.Component
{
componentDidMount() {
this.props.actions.requestPosts();
}
render() {
return(
<div className="main-page">
<PreviewList posts={this.props.posts}/>
</div>
);
}
}
const mapStateToProps = state => ({
posts: state.main_posts,
errors: state.main_errors
});
const mapDispatchToProps = dispatch => {
return {
actions: {
requestPosts: () => dispatch(requestPosts())
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(MainPage);
减速器:
export default (state = {main_posts: [], main_errors: []}, action) => {
switch(action.type) {
case USER_REQUESTS_POSTS_SUCCEEDED:
return Object.assign({}, state, {
main_posts: action.posts
});
case USER_REQUESTS_POSTS_FAILED:
return Object.assign({}, state, {
main_errors: action.errors
});
default:
return state;
}
};
为了简单起见,我没有包含import语句。我使用redux-thunk。我已经测试了这些动作,他们成功地到达了减速器。成功创建并返回新状态。然而,它根本没有到达所需的组件。
我尝试过研究,而且我只找到了改变状态的减速器的例子,但是我无法看到任何改变状态的地方。我究竟做错了什么? (具有讽刺意味的是,代码与我的其他反应应用程序类似,可以正常工作)。
如果它有用,这是我的商店:
export const history = createHistory();
const middleware = [
thunk,
routerMiddleware(history)
];
const reducers = {
main: mainReducer,
router: routerReducer
};
const store = createStore(
combineReducers(reducers),
{},
applyMiddleware(...middleware)
);
export default store;
编辑:根据要求,以下是我的行动:
export const USER_REQUESTS_POSTS_SUCCEEDED = 'user/REQUESTS/POSTS/SUCCESS';
export const USER_REQUESTS_POSTS_FAILED = 'user/REQUESTS/POSTS/FAILURE';
export const requestPosts = () => {
return function(dispatch) {
return fetchPosts().then(
posts => dispatch(requestPostsSucceeded(posts)),
errors => dispatch(requestPostsFailed(errors))
);
};
};
function fetchPosts() {
return Promise.resolve([{title: 'Test Post', content_short: 'Hello World', author: 'Extremo', category: 'development', tags: ['test'], date: '15.11.17'}]);
}
export const requestPostsSucceeded = (posts) => {
return {type: USER_REQUESTS_POSTS_SUCCEEDED, posts: posts};
};
export const requestPostsFailed = (errors) => {
return {type: USER_REQUESTS_POSTS_FAILED, errors: errors};
};
答案 0 :(得分:0)
您的mapStateToProps
功能应该是:
function mapStateToProps(state) {
return {
posts: state.main.main_posts,
errors: state.main.main_errors
}
}
您正在传递帖子和错误,目前为undefined
答案 1 :(得分:0)
从商店定义
const reducers = {
main: mainReducer,
router: routerReducer
};
您应该使用component reducer's key
是main
。
const mapStateToProps = state => ({
posts: state.main.main_posts,
errors: state.main.main_errors
});