组件异步获取redux状态?

时间:2018-10-16 12:34:36

标签: reactjs redux react-redux

我对redux状态有疑问。分页组件具有方法

const setPage = page => {
    props.removeFilterParam('page');
    props.addFilterParam('page', page);
    props.getProducts();
}

props.removeFilterParamprops.addFilterParam是修改redux存储的redux操作,getProducts是父组件上的方法,看起来像这样

async getProducts() {
    try {
        console.log('Filter before', this.props.filter);
        setTimeout(() => console.log('After', this.props.filter), 2000)
        // const slug = this.props.match.params.slug;
        // const queryString = transformToQueryString(this.props.filter);
        // await this.props.getProductsRequest(`/api/categories/${slug}/${queryString}`);
    } catch (error) {
        console.error(error);
    }
}

父组件与Redux存储连接。在控制台中调用getProducts时,我会看到以下信息:

enter image description here

因此,在通过addFilterParam修改redux状态之后,所做的更改将不会同步应用于getProducts函数中。

动作是:

export const addFilterParam = (name, value) => ({
    type: ADD_FILTER_PARAM,
    name,
    value
})

export const removeFilterParam = (name, value) => ({
    type: REMOVE_FILTER_PARAM,
    name,
    value
});

Reducer是:

const filterReducer = (state = {}, action) => {
    switch(action.type) {
        case ADD_FILTER_PARAM:
            if (state.hasOwnProperty(action.name)) {
                if (Array.isArray(action.value)) {
                    state[action.name] = [...state[action.name], ...action.value];
                } else {
                    if (state[action.name].indexOf(action.value) === -1) {
                        state[action.name].push(action.value);
                    }
                }
            } else {
                if (Array.isArray(action.value)) {
                    state[action.name] = action.value;
                } else {
                    state[action.name] = [action.value];
                }
            }
            return {...state};

        case REMOVE_FILTER_PARAM:
            if (state.hasOwnProperty(action.name)) {
                if (action.value) {
                    let args = state[action.name];
                    const index = args.indexOf(action.value);

                    if (index !== -1) {
                        args.splice(index, 1);

                        if (args.length) {
                            state[action.name] = args;
                        } else {
                            delete state[action.name];
                        }
                    }
                } else {
                    delete state[action.name];
                }
            }

            return {...state};

        case CLEAR_FILTER:
            return {};

        default: return state; 
    }
}

1 个答案:

答案 0 :(得分:1)

Redux操作不同步。他们不会即时更改您的组件道具。他们所做的是触发可以更改减速器的动作(就像做出//variable declaration and loop above alert(sum/2); it's not synchronous一样)。他们肯定会在下一个setState通话中被更改。如果您需要在更改道具时收到通知,则可以使用componentDidUpdate()回调。在您的示例中:

render()
相关问题