【发布时间】:2019-11-26 13:40:20
【问题描述】:
我在一个组件中有一个 .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}
/>
))
);
当我发布一个项目时,有时(并非总是)它会在视图中重复,但不会在数据库中重复。 DB 工作正常,但不知何故,在我发布项目后,它并不总是正确设置项目, 这是动作和减速器:
//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 是唯一的,为什么会这样?
还有购物项目组件:
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));
【问题讨论】:
-
尝试在每次发布项目时发送
GET_ITEMS并展示发生了什么! -
代码中已经这样做了:
handleSubmit = event => { event.preventDefault(); const newItem = { name: this.state.name, handler: this.props.user.user.name }; this.props.postItem(newItem); this.props.getItems(); };
标签: javascript arrays reactjs ecmascript-6 redux