gpt4 book ai didi

javascript - 组件无法跟上 redux 状态

转载 作者:行者123 更新时间:2023-12-03 02:20:43 26 4
gpt4 key购买 nike

请帮我解决这个问题。我使用 redux 和 react-redux 来控制应用程序中的状态。但是,当我尝试根据 redux 存储中的值更改组件中的样式时,它会出现延迟 react 。当我添加新项目并单击列表并期望其颜色发生变化时,它仅在我添加另一个项目后才会执行此操作,因此它总是会延迟。这是我的 reducer

export const items = (state = [], action) => {
switch(action.type) {
case 'ADD_ITEM':
const newItem = {
title: action.title,
id: action.id,
selected: action.selected,
comments: action.comments
};
return [
...state,
newItem
];
case 'REMOVE_ITEM':
return state.filter(({ id }) => id !== action.id);
case 'SELECT_ITEM':
state.map((item) => {
if (item.id === action.id) {
return [
...state,
item.selected = true
];
} else {
return [
...state,
item.selected = false
];
}
});
default:
return state;
}
};

这是我的组件,我想对 redux 存储的每次更改使用react

import React from 'react';
import { connect } from 'react-redux';
import { removeItem, selectItem } from '../actions/items';
import { Badge, ListGroup, ListGroupItem, Button } from 'reactstrap';

const stylesForActiveItem = {
borderLeft: '4px solid red',
transition: 'all .5s',
marginLeft: '-4px',
borderRadius: '0'
}

class Item extends React.Component {
constructor(props) {
super(props);
}
render() {
const { removeItem, selectItem, id, title, selected } = this.props;
return (
<ListGroup className="Item">
<ListGroupItem
onClick={() => selectItem({ id })}
className={selected ? 'Item__text active-item' :
'Item__text'}
>{title} <Badge className="Item__badge">14</Badge>
</ListGroupItem>
<Button className="Item__btn" onClick={() => removeItem({ id
})}>Delete</Button>
</ListGroup>
);
}
}

const mapDispatchToProps = (dispatch) => ({
removeItem: (id) => dispatch(removeItem(id)),
selectItem: (id) => dispatch(selectItem(id))
})

export default connect(null, mapDispatchToProps)(Item);

最佳答案

  state.map((item) => {
if (item.id === action.id) {
return [
...state,
item.selected = true
];
} else {
return [
...state,
item.selected = false
];
}
});

//I guess you need to do something like this



state.map((item) => {
if (item.id === action.id) {
return {...item, selected:true}

} else {
return {...item, selected:false}

}
});

因为即使map返回新数组,内部对象也不应该被改变。这就是我们在内部传播并创建一个新项目对象的原因。无需在具有完整状态的 map 中再次创建数组。这只会改变你的状态结构,而不仅仅是改变 bool 值。

关于javascript - 组件无法跟上 redux 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49172058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com