更新:没有调用 Redux reducer 来改变 CSS 类

Update: Redux reducer is not beeing called to change CSS classes

我是 redux 和 react-redux 的新手。
当用户单击动态呈现的 <div> 标签时,我试图更改 CSS 类。当我尝试在本地设置状态时,代码正在运行,但是当我想使用 redux 时,我得到了应该存储 event.target.id 的数组的未定义值。你能告诉我我哪里错了吗? 我将从行动开始:

export const selectAttr = (e)=>{     
    return (dispatch) => {
        return(
            dispatch({
                type: SELECT_ATTRIBUTES,
                payload: e.target.id
            })
        )
    }
}

减速器:

 const initialState = {
    selectedAttr: [],
}
 

export default function selectAttrReducer (state = initialState, action) {
    let tmp = [...state.selectedAttr]
    function attributes() {
        if (tmp.length === 0) {
            tmp = [...tmp, action.payload];
            return tmp;
        } else {
            for (let i = 0; i < tmp.length; i++) {
                if (action.payload.split(":")[0] === tmp[i].split(":")[0]) {
                    tmp = [...tmp.filter(el => el.split(":")[0] !== action.payload.split(":")[0]), action.payload];

                } else {
                    tmp = [...tmp, action.payload];
                }
            }
            return tmp;
        }
    }
    switch(action.type){
        case SELECT_ATTRIBUTES:
           attributes()
            return {
                ...state,
                selectedAttr: [...state.selectedAttr, ...tmp]
            }
        default:
            return state    
    }
}

JSX 片段:

<div>
    {attributes.map((attr, index) => (
        <div key={attr.id}>
            {/* attribute name */}
            <p className="pdp-attr">{attr.name}:</p>

            {/* attribute representation */}
            <div className="swatch-flex">
                {attributes[index].items.map((item) => (
                    <div key={item.id}>
                        <div
                            onClick={this.props.selectAttr}
                            className={
                                selectedAttr?.indexOf(
                                    attributes[index].id.concat(":", item.id)
                                ) === -1
                                    ? "pdp-box"
                                    : "pdp-box isSelected"
                            }
                            id={attributes[index].id.concat(":", item.id)}></div>
                    </div>
                ))}
            </div>
        </div>
    ))}
</div>

const mapStateToProps = (state) => {
    return {
        selectedAttr: state.selectedAttr,
    };
};

export default connect(mapStateToProps, { selectAttr })(Component);

更新:
看起来好像调用了 reducer,但是 selectedAttr 数组有数千个项目。我也更新了代码。
我也在使用 redux-persist。可以,就因为这个?

您确定没有调用减速器吗?

这段代码是错误的:

return {
    ...state, ...tmp
}

(不要)* 试试这个: 请参阅@nlta 的评论。

// must wrap in parenthesis to return an object
return ({
    ...state, ...tmp
})

reducer 被调用了,但因为它是一个“纯”函数,(Rules of reducers) 我将 filter 方法移到了选择器中。