我正在玩react,redux,react-redux和redux-sagas。我有一个组件,一旦安装执行API调用,并且在执行调用时,应该在组件中添加数据。
如果我理解正确,
mapDispatchToProps
用于在组件dispatch
函数
mapStateToProps
用于在更改react的存储时更新组件sagas
用于在将消息发送到redux时触发异步功能reducers
用于在将消息发送到redux时更改react的存储但是,在我的项目中,当安装组件时,会触发API调用,更改存储,但不会调用mapStateToProps
,因此我的组件不会显示结果。
我不知道如何调试它。
我错过了什么吗?
sagas/index.js
function* loadLinks(action) {
try {
const links = yield call(linksSearch, action.value);
yield put({type: "LINKS_LOAD_SUCCEEDED", links: links, page: action.value.page});
} catch (e) {
yield put({type: "LINKS_LOAD_FAILED", message: {}});
}
}
function* mySaga() {
yield [
takeEvery("LINKS_LOAD_REQUESTED", loadLinks)
]
}
export default mySaga;
reducers/index.js
const addLinks = (links, page, state) => {
const newLinks = [page].reduce((init, page) => {
init[page]=links;
return init;
}, state);
return Object.assign(newLinks)
};
const requestedLinks = (state = {}, action) => {
switch (action.type) {
case 'LINKS_LOAD_SUCCEEDED':
const newState = addLinks(action.links, action.page, state);
return newState;
default:
return state;
}
};
const reducer = combineReducers({
requestedLinks,
});
export default reducer
containers/ConnectedLinksGrid.js
const mapStateToProps = (state, ownProps) => {
return {
links:
(ownProps.page in state.requestedLinks) ?
state.requestedLinks[ownProps.page] :
[]
}
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
loadLinks: () => {
const value = ownProps;
dispatch({type: "LINKS_LOAD_REQUESTED", value})
}
}
};
const ConnectedLinksGrid = connect(
mapStateToProps,
mapDispatchToProps
)(LinksGrid);
export default ConnectedLinksGrid;
注意:<LinksGrid />
一旦挂载就调用loadLinks()。
答案 0 :(得分:4)
看起来你的reducers文件中的addLinks
函数正在使用行init[page]=links;
直接修改状态,这意味着当你的reducer返回新状态时,redux会将新状态与旧状态进行比较状态,没有区别,这意味着您的组件不会更新。
此外,您不应该需要addLinks功能的复杂性。您可以像这样更新主减速器功能:
const requestedLinks = (state = {}, action) => {
switch (action.type) {
case 'LINKS_LOAD_SUCCEEDED':
return Object.assign({}, state, {
[action.page]: action.links,
});
default:
return state;
}
};