我一直在嘗試使用Reacts組件功能來創建組件。在這種情況下,我對componentDidMount特別感興趣。Redux狀態不會傳播到組件
但是,無論我嘗試什麼,我的狀態都不會傳播到組件。
以下是部分:
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};
};
你能告訴我們'requestPosts'嗎? – nem035
@ nem035我更新了我的問題。但請記住,減速器確實收到帖子,並且會在帖子中產生新的狀態。 – Extremo
然後你是否使用[''](https://github.com/reactjs/react-redux/blob/master/docs/api.md#provider-store)? –
nem035