我在组件中有一个.map函数:
let recentItemsMarkup = loading ? (
<p>Items are loading...</p>
) : (
items.map(item => (
<ShoppingItem
key={item._id}
id={item._id}
name={item.name}
createdAt={item.date}
/>
))
);
当我发布一个项目时,有时-并非总是-它在视图上重复,但在数据库中不是。数据库工作正常,但是以某种方式,在我发布项目后,它并不总是能正确设置项目,
这里是动作和减速器:
//post item
export const postItem = newItem => dispatch => {
dispatch({ type: LOADING_UI });
axios
.post("http://localhost:5000/api/items", newItem)
.then(res => {
dispatch({
type: POST_ITEM,
payload: res.data
});
})
.catch(err => {
dispatch({
type: SET_ERRORS,
payload: err.response.data
});
});
};
和减速器:
const initialState = {
items: [],
item: {},
loading: false
};
export default (state = initialState, action) => {
switch (action.type) {
case LOADING_ITEMS:
return {
...state,
loading: true
};
case GET_ITEMS:
return {
...state,
items: action.payload,
loading: false
};
case POST_ITEM:
return {
...state,
items: [action.payload, ...state.items]
};
case DELETE_ITEM:
return {
...state,
items: state.items.filter(item => item._id !== action.payload)
};
default:
return state;
}
};
我检查了ID和数据库,一切正常,ID是唯一的,为什么会这样?
screenshot
以及Shopping Item组件:
class ShoppingItem extends Component {
render() {
const { authenticated } = this.props.user;
const { name, createdAt, classes, id } = this.props;
const deleteButton = authenticated ? (
<DeleteItem id={id} />
) : null;
return (
<Card className={classes.card}>
<CardContent>
<Typography variant="body1" color="textPrimary">
{this.props.id}
</Typography>
<Typography variant="body1" color="textPrimary">
{name}
</Typography>
{deleteButton}
<Typography color="textSecondary">
{dayjs(createdAt).format("h:mm a, MMM DD YYYY")}
</Typography>
</CardContent>
</Card>
);
}
}
ShoppingItem.propTypes = {
name: PropTypes.string.isRequired,
};
const mapStateToProps = state => ({
user: state.user
});
const actionsToProps = {
deleteItem
};
export default connect(
mapStateToProps,
actionsToProps
)(withStyles(styles)(ShoppingItem));
最佳答案
似乎您的后端会返回一系列项以及新项,因此在这种情况下,您只需将其设置为状态,而不是添加到现有项中:
case POST_ITEM:
return {
...state,
items: action.payload
};
关于javascript - react -Redux; .map函数有时会复制数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59052260/