更新状态内的对象

时间:2018-02-08 10:16:53

标签: javascript reactjs

我有3个不同的api来打电话。每个api以json格式返回某个值。我想使用这些值来构建图表。

class ScreenView extends Component {

    constructor(){
        super();
        this.state = {
            newUsersToday:'',
            totalUsers:'',
            totalApplicationOnLiveAdvt:'',
            chartData:{
                newuserstoday:'',
                candidatesOnliveAdvt:'',
                totalsignuptilltoday:''
            }
        }
    }

    componentDidMount(){
        let url ="http://localhost:7080/newuserstoday";
        getAllData(url).then(response =>
             this.setState({newUsersToday:response.data.newuserstoday},()=>{
            console.log(this.state.chartData.newuserstoday);
        }));

        let chartData = Object.assign({},this.state.chartData);
        chartData.newuserstoday=this.state.newUsersToday;
        this.setState({chartData});

        let url2 = "http://localhost:7080/candidatesOnliveAdvt";
        getAllData(url2).then(response => 
            this.setState({totalApplicationOnLiveAdvt:response.data.TotalCandidateOnLiveAdvt},()=>{
            console.log("fetched data ", this.state.totalApplicationOnLiveAdvt);
        }));

        let url3 ="http://localhost:7080/totalsignuptilltoday";
        getAllData(url3).then(response => this.setState({totalUsers:response.data.Users},()=>{
            console.log("fetched data ", this.state.totalUsers);
        }));

    }

    render(){
        return(
        <div>
            <Navbar/>
            <div className="container">
                <div className="row">
                    <div className="col-sm-4 py-10 px-10">
                        <Card message="Total Signup Today" data={this.state.newUsersToday}/>
                        <Card message="Total Application on Live Advt" data={this.state.totalApplicationOnLiveAdvt}/>
                        <Card message="Total Candidates" data={this.state.totalUsers}/>
                    </div>
                </div>
            </div>
        </div>
        );
    }
}

export default ScreenView;

我试图在state和frameData对象中的相应变量上设置每个值。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

const newChartData = {...this.state.chartData}
this.setState({
  ...this.state,
      chartData: {
        ...newChartData,
        newuserstoday: response.data.newuserstoday
      }
})

这就是你如何为newuserstoday做到这一点。同样你可以为其他人做。希望这有帮助