Object passed into Redux store is not reflecting a

2019-08-17 01:59发布

问题:

I have a component where toggle buttons are dynamically generated. Right now, I am just trying to get it working at a basic level so you click on a button and it adds a key/value pair to the cuts = {}.

After clicking on multiple buttons the cuts should have several key/value pairs: it does in the component where cuts resides, it does in the action, and it does in the Redux store via console.log(state.cuts).

However, after mapStateToProps it is only showing the first value and I am not sure why.

Anyway, here is my code and the flow as it is initiated by the user:

// 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;

// bq_results.js component where the FILTER_RESULTS is accessed
render() {
    console.log(this.props.filter_results); // only shows the first result
    return (<div>...</div>)
}


function mapStateToProps(state) {
    console.log(state.results.filter_results); // shows all selected cuts here
    return {
        filter_results: state.results.filter_results,
    }
}

Maybe a better way of putting it is it seems like after the initial state is mapped to props, it is no longer receiving changes to state and mapping it to props.

回答1:

Came across this article and used Approach #2:

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

Ended up with:

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

}