分派操作和状态更新时不重新渲染的组件

Components Not Re-Rendering when Action is Dispatched and State Updates

当我单击我的 InspectorOption 组件之一时,我的 redux 记录器显示已分派一个操作并且状态按预期更新。

我的 InspectorSelect 和子 InspectorOption 组件使用 react-redux 连接到 mapStateToProps,这些组件依赖于来自状态的那些道具。

但是即使状态正在更新并且组件依赖于状态,组件也不会在状态更新时重新渲染。

为什么当状态改变时我的组件没有重新渲染,我该如何纠正这个问题?

@connect((state) => {
    return {
        options: state.inspector.options
    }
})
export default class InspectorSelect extends Component {
    render() {
        return (
            <div>
                {
                    this.props.options.map(option => {
                        return <InspectorOption 
                            option={ option }
                            key={ option.id }
                        />
                    })
                }
            </div>
        )
    }   
}

https://github.com/caseysiebel/dashboard/blob/master/src/components/InspectorSelect.js#L17

正如@markerikson 指出的:99.9% 的时间,这是由于 reducer 中 Redux 状态的意外突变

dashboard/src/reducers/inspector.js

有突变
export default function reducer(state = {
    options: [] 
}, action) {

    switch (action.type){
        case 'SET_INSPECTOR': 
            state.options = state.options.map(option => {   // <-- mutation here
                return option.id === action.payload ?
                    { ...option, active: true } :
                    { ...option, active: false }
            })
            return state // returning mutated state
        default: 
            return state
    }
}

应该是

export default function reducer(state = {
    options: [] 
}, action) {

    switch (action.type){
        case 'SET_INSPECTOR': 
            var newOptions = state.options.map(option => {
                return option.id === action.payload ?
                    { ...option, active: true } :
                    { ...option, active: false }
            });
            return {...state, options: newOptions}  // returning new state
        default: 
            return state
    }
}