Redux 我该如何改变;这";对象

Redux 我该如何改变;这";对象,redux,axios,Redux,Axios,我知道这个对象不能更改,但需要另一种方法 var that= this axios.get('http://ec2-54-165-240-14.compute-1.amazonaws.com:3000/api/foodItem').then(function(data){ console.log("inside axios ",data) that.setState({ items : data,

我知道
这个
对象不能更改,但需要另一种方法

var that= this
        axios.get('http://ec2-54-165-240-14.compute-1.amazonaws.com:3000/api/foodItem').then(function(data){
            console.log("inside axios ",data)
            that.setState({
                items : data,
            });
            var curGroupId = that.props.cartReducer.val;
            var items = that.state.items ;
            var curItems= [];
            for(var i in items){
                if(items[i].food_group_id==curGroupId){
                    curItems.push(items[i]);
                }
            }
            that.setState({
                curItems : curItems
            })

        }).catch(function(err){
            console.log(err)
        })

我想更新
对象中的状态,该状态在
then
函数中不可访问,因此我已将
对象存储在
函数之前,但我想在
对象中应用更改。

您可以尝试使用箭头函数,这样,您就可以在内部函数中访问此

axios.get('http://ec2-54-165-240-14.compute-1.amazonaws.com:3000/api/foodItem')
   .then((data) => {
        console.log("inside axios ",data)
        this.setState({  // <---- references to the parent scope
            items : data,
        });
        var curGroupId = that.props.cartReducer.val;
        var items = that.state.items ;
        var curItems= [];
        for(var i in items){
            if(items[i].food_group_id==curGroupId){
                curItems.push(items[i]);
            }
        }
        this.setState({   // this too ;)
            curItems : curItems
        })

    }).catch((err) => {
        console.log(err)
    })
axios.get('http://ec2-54-165-240-14.compute-1.amazonaws.com:3000/api/foodItem')
。然后((数据)=>{
console.log(“axios内部”,数据)
此.setState({//{
console.log(错误)
})
箭头函数将使用与父函数相同的作用域,在这些情况下非常方便


还有一件事,我不建议多次调用
setState
。当所有数据都可以使用时,您应该在回调结束时只调用它一次。

您可以尝试使用arrow函数,这样您就可以访问内部函数中的
this

axios.get('http://ec2-54-165-240-14.compute-1.amazonaws.com:3000/api/foodItem')
   .then((data) => {
        console.log("inside axios ",data)
        this.setState({  // <---- references to the parent scope
            items : data,
        });
        var curGroupId = that.props.cartReducer.val;
        var items = that.state.items ;
        var curItems= [];
        for(var i in items){
            if(items[i].food_group_id==curGroupId){
                curItems.push(items[i]);
            }
        }
        this.setState({   // this too ;)
            curItems : curItems
        })

    }).catch((err) => {
        console.log(err)
    })
axios.get('http://ec2-54-165-240-14.compute-1.amazonaws.com:3000/api/foodItem')
。然后((数据)=>{
console.log(“axios内部”,数据)
此.setState({//{
console.log(错误)
})
箭头函数将使用与父函数相同的作用域,在这些情况下非常方便

还有一件事,我不建议多次调用
setState
。在回调结束时,当您的所有数据都可以使用时,您应该只调用一次。

Thank:)对我有效。yes将记住这一点Thank:)对我有效。yes将记住这一点