传递到Redux存储的对象不反映mapStateToProps之后的所有键/值

时间:2018-04-04 00:04:09

标签: reactjs redux react-redux

我有一个组件,其中动态生成切换按钮。现在,我只是想让它在基本级别工作,所以你点击一个按钮,它会为cuts = {}添加一个键/值对。

点击多个按钮后,cuts应该有几个键/值对:它在cuts所在的组件中,在操作中执行,在Redux商店中通过{ {1}}。

然而,在console.log(state.cuts)之后,它只显示第一个值而我不确定原因。

无论如何,这是我的代码和用户发起的流程:

mapStateToProps
// bq_cuts.js component
constructor(props) {
    super(props);
    this.state = {
        cuts: {}
    }
}

onCutSelect(cut) {
    const { bqResults } = this.props;
    const { cuts } = this.state;

    let key = cut.name;
    let value = cut.value;

    cuts[key] = value;
    this.setState({
        cuts
    })
    console.log(cuts); // shows all of the selected cuts here
    bqResults(cuts);
}
// results.js actions
export function bqResults(results) {
    console.log(results); // shows all of the selected cuts here
    return function(dispatch) {
        dispatch({
            type: FILTER_RESULTS,
            payload: results
        })
    }
}
// results.js reducer
import {
    FILTER_RESULTS
} from '../actions/results';

export default function(state = {}, action) {
    switch(action.type) {
        case FILTER_RESULTS:
            console.log(action.payload); //prints out all the cuts
            return {
                ...state,
                filter_results: action.payload
            }
        default:
            return state;
    }

    return state;
}

const rootReducer = combineReducers({
    results: resultsReducer,
});

export default rootReducer;

也许更好的方法是将初始状态映射到道具后,它不再接收状态更改并将其映射到道具。

1 个答案:

答案 0 :(得分:0)

看过这篇文章并使用方法#2:

https://medium.freecodecamp.org/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5

结束于:

onCutSelect(cut) {
    let cuts = {...this.state.cuts, [cut]: cut}
    this.setState({
        cuts
    }, () => this.props.bqResults(this.state.cuts));

}