【发布时间】:2019-03-28 19:14:03
【问题描述】:
此组件在其状态中有一个对象数组,并带有属性“userFavorites”。
userFavorites: [{id: 1, title: 'A'}, {id: 2, title: 'B'}]
当我调用 postFavorite() 时,我需要向“userFavorite”添加一个新对象。
我正在使用 prevState 和扩展运算符设置状态。
无论我通过调用 postFavorite() 更新状态多少次,我的 prevState 参数总是相同的。 prevState 总是相同的,只有添加到数组中的最后一个对象会保留在那里。
有人能发现我的问题吗?
class Albums extends React.Component {
constructor(props) {
super(props);
this.state = {
userLoggedId: null,
renderFavorites: false,
userFavorites: []
}
this.getDetails = this.getDetails.bind(this);
}
componentDidMount() {
const state = JSON.parse(window.localStorage.getItem('albumsStore'));
if(state) {
this.setState(() => ({ userLoggedId: state.userLoggedId, renderFavorites: state.renderFavorites, userFavorites: state.userFavorites }));
}
}
componentDidUpdate(prevProps) {
if(this.props !== prevProps) {
this.setState(() => ({ userLoggedId: this.props.userLoggedId, renderFavorites: this.props.renderFavorites, userFavorites: this.props.userFavorites }));
}
window.localStorage.setItem('albumsStore', JSON.stringify(this.state));
}
setFavorite(event, favorite) {
event.stopPropagation();
this.postFavorite();
}
postFavorite = async() => {
const post = await postFavorite(this.state.userLoggedId, this.props.id);
if(post.status === 200) {
this.setState( prevState => ({
userFavorites: [...prevState.userFavorites, {id: this.props.id}]
}));
} else {
console.log("Something went wrong");
}
}
isFavorite(id) {
return this.state.userFavorites.find(favorite => favorite.id === id) ? true : false;
}
render() { ... }
这是我在触发此方法的两个不同“元素”中两次调用“postFavorite”后的日志:
【问题讨论】:
-
看起来您将用户收藏夹作为道具传递给构造函数中的状态,然后在 componentDidMount 中将其重置。我会看一下,至少删除 cDM 中重置的用户收藏夹...希望这会有所帮助。
-
@MarcM。我没有在 cDM 中重置“userFavorites”。我将状态设置为我保存在 localStorage 中的状态。我需要保持状态并且我正在使用 localStorage。
-
您是从
postFavorite拨打postFavorite吗?你确定你没有搞砸吗? -
@AsafAviv 它没有“this.”,可能是一个外部函数。我在内部函数中使用下划线来区别于外部导入函数。
-
您是否尝试评论 componentDidUpdate 函数?试试这个看看状态是否正确更新。
标签: javascript reactjs setstate