组件未在道具上重新渲染以更改Redux反应

时间:2020-05-04 13:01:39

标签: reactjs redux

在Redux状态更改后,带有过滤器的组件不会重新呈现。使用console.log(),我可以看到该动作和减速器起作用。更改后的ObjectFilter.js可以在控制台上获得良好的效果,但不会重新呈现。

mapReducer.js

const mapReducer = (state = initState, action) => {
    switch(action.type) {
        case actions.SET_FILTERS:
            console.log('SET_FILTERS', state)
            return({
                ...state,
                filters: action.filters
            })
        default:
            return state;
    }
}

export default mapReducer;

mapActions.js

export const setFilters = (el, old_filters) => {
    let filters = old_filters;
    let new_el = !old_filters[el];

    filters[el] = new_el;
    console.log(filters)
    return (dispatch, getState) => {
        dispatch({
            type:actions.SET_FILTERS,
            filters: filters
        })
    }
}

objectFilters.js

class ObjectFilters extends Component {


    changeFilterHandler = (el) => {
        this.props.setFilters(el, this.props.filters);
    }

    render () {
        console.log(this.props.filters)
        return (
        /* some code */
    );}
}

const mapDispatchToProps = dispatch => {
    return {
        setFilters: (el, filters) => dispatch(setFilters(el, filters))
    }
}

const mapStateToProps = state => {
    return {
        filters: state.mapRedux.filters
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ObjectFilters);

1 个答案:

答案 0 :(得分:2)

您的代码中的问题是您要直接突变old_filters,而不是对其进行克隆,然后更新过滤器值。 切勿直接改变状态和道具

export const setFilters = (el, old_filters) => {
    let filters = {...old_filters}; // using spread operator to create a clone
    let new_el = !old_filters[el];
    filters[el] = new_el;

    return (dispatch, getState) => {
        dispatch({
            type:actions.SET_FILTERS,
            filters: filters
        })
    }
}