此组件的状态为对象数组,其属性为' 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”后的日志:
答案 0 :(得分:0)
在 componentDidUpdate 中,可能是问题所在。通常,如果需要使用newProps更新状态, componentWillReceiveProps 会很有帮助。
if(this.props !== prevProps) {
请尝试以下组件。希望它会有所帮助。
class Albums extends React.Component {
constructor(props) {
super(props);
this.state = {
userLoggedId: null,
renderFavorites: false,
userFavorites: []
}
this.getDetails = this.getDetails.bind(this);
}
componentWillReceiveProps(nextProps){
this.setState(() => ({ userLoggedId: nextProps.userLoggedId, renderFavorites: nextProps.renderFavorites, userFavorites: nextProps.userFavorites }));
}
componentDidMount() {
const state = JSON.parse(window.localStorage.getItem('albumsStore'));
if(state) {
this.setState(() => ({ userLoggedId: state.userLoggedId, renderFavorites: state.renderFavorites, userFavorites: state.userFavorites }));
}
}
componentDidUpdate() {
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() { ... }