在react-redux中的reducers之后,不会触发`mapStateToProps`

时间:2017-03-26 14:25:25

标签: javascript reactjs redux redux-saga

我正在玩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()。

1 个答案:

答案 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;
    }
};