`mapStateToProps` 在 react-redux 中的 reducers 之后没有被触发

`mapStateToProps` is not triggered after reducers in react-redux

我正在玩 react、redux、react-redux 和 redux-sagas。我有一个组件,一旦挂载就会执行 API 调用,执行调用时,应该在组件中添加数据。

如果我没理解错的话,

但是,在我的项目中,当组件挂载时,触发了API调用,改变了store,但没有调用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()。

看起来你的 reducer 文件中的 addLinks 函数直接用行 init[page]=links; 修改状态,这意味着当你的 reducer 然后 returns 新状态和 redux 比较新状态到旧状态,没有区别,这意味着你的组件没有更新。

此外,您不需要复杂的 addLinks 函数。您可以像这样更新主减速器功能:

const requestedLinks = (state = {}, action) => {
    switch (action.type) {
        case 'LINKS_LOAD_SUCCEEDED':
            return Object.assign({}, state, {
              [action.page]: action.links,
            });
        default:
            return state;
    }
};