使用setState方法设置状态的对象值

时间:2020-05-20 14:17:28

标签: reactjs typescript react-lifecycle

我在React中有一个对象作为状态变量。我想使用setState方法更改其各种值,但它显示了。虽然我可以使用this.state方法进行设置,但是我猜这不是正确的方法。请提出我该怎么做。


 this.state={
            graphData:{
                labels:['4 P.M','5 P.M','6 P.M','7 P.M','8 P.M','9 P.M','10 P.M','11 P.M','12 A.M','1 A.M','2 A.M','3 A.M','4 A.M'],
                datasets:[
                    {
                    label:"Day",
                    backgroundColor:"#F6ABE4",
                    borderColor:'#333',
                    borderWidth:2,
                    lineTension:0.1,
                    fill:true,
                    data:[4,5,6,7,8,9,10,11,12,1,2,3,4]

                    }


                ]
            }
}

 this.setState({[graphData.datasets[0].backgroundColor]:"#F6ABE4"})


this.setState((state) => ({
                    graphData : {
                        ...state.graphData ,
                        datasets : [

                            // First slice of array before the index we want to change
                            ...state.graphData.datasets.slice(0, 5),

                            // changing the element on the given index
                            {
                                ...state.graphData.datasets[0] ,
                                // you can modify all the properties you want
                                data : result // <------ CHANGE HERE
                            },

                            // rest of the array elements after index
                            ...state.graphData.datasets.slice(6+1)
                        ]
                    }
                }))

2 个答案:

答案 0 :(得分:1)

在这里,您可以执行以下操作:

this.setState((state) => ({
    graphData : {
        ...state.graphData ,
        datasets : [

            // First slice of array before the index we want to change
            ...state.graphData.datasets.slice(0, index),

            // changing the element on the given index
            {
                ...state.graphData.datasets[index] ,
                // you can modify all the properties you want
                backgroundColor : "#F6ABE4" // <------ CHANGE HERE
            },

            // rest of the array elements after index
            ...state.graphData.datasets.slice(index+1)
        ]
    }
}))

希望代码注释可以消除疑问

答案 1 :(得分:0)

您也可以尝试以下方法:

const { graphData } = this.state;
graphData.datasets[0].backgroundColor = "#F6ABE4";
this.setState({ 
   graphData
})