我是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
。可以,因为这个?
您确定没有调用reducer吗?
此代码错误:
return {
...state, ...tmp
}
(不要(*试试这个:查看@nlta的评论。
// must wrap in parenthesis to return an object
return ({
...state, ...tmp
})
调用了reducer,但因为它是一个"纯";函数,(减速器规则(我在选择器内部移动了filter方法。