【问题标题】:setState() doesn't update my state properlysetState() 没有正确更新我的状态
【发布时间】: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


【解决方案1】:

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() { ... }

【讨论】:

  • 问题依然存在。您对 componentWillReceiveProps 的建议与我对 componentDidUpdate 所做的相同。 React atm 认为 componentWillReceiveProps 是“_unsafe”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 2018-08-11
  • 2020-03-03
  • 1970-01-01
  • 2019-06-07
  • 2019-01-28
相关资源
最近更新 更多