简体   繁体   English

json对象的setState提供了未定义的[反应]

[英]setState from json object gives undefined [React]

So i got this problem where i get an response from my backend and i parse it to json then call my set function like this 所以我遇到了这个问题,我从后端得到响应并将其解析为json然后像这样调用我的set函数

try{
    const leaderboardInfo: LeaderboardState = JSON.parse(response);
    this.onLeaderboardStateUpdate(leaderboardInfo);
    console.log(leaderboardInfo);
}
catch(e){
    console.log(`Failed to convert: ${response} into a JS object`);
}

And the console.log gives me this response 而console.log给了我这个回应

在此处输入图片说明

So so far so good its the LeaderboardConfig that i want to use to set the state. 到目前为止,到目前为止,我想使用它来设置状态的LeaderboardConfig很好。

My setState function is just an basic one 我的setState函数只是一个基本的函数

onLeaderboardStateUpdate(state: LeaderboardState): void
{
    this.setState({leaderboardState: state})
}

and my state looks like this 我的状态看起来像这样

this.state = {
    leaderboardState: {LeaderboardId: 0,LeaderboardName:"",StartDate:"",EndDate: ""}
};

but for some reason this gives undefined so it seems not be able to setState from the json object i have 但是由于某种原因,它给出了undefined,因此似乎无法从我拥有的json对象中获取setState

for your information as well leaderboardState is an interface which looks like this. 对于您的信息,leaderboardState是一个类似于以下的接口。

export interface LeaderboardState {
    LeaderboardId: number
    LeaderboardName: string
    StartDate: string
    EndDate: string
}

What Jai said made me solve it i had to change the try catch to this Jai所说的让我解决了这个问题,因此我不得不将尝试方法更改为此

try{
    const leaderboardInfo = JSON.parse(response);
    this.onLeaderboardStateUpdate(leaderboardInfo.LeaderboardConfig[0]);
    console.log(leaderboardInfo);
        }
        catch(e)
        {
            console.log(`Failed to convert: ${response} into a JS object`);
        }

Removing the LeaderboardState interface here and going into LeaderBoardConfiguration which when i had the interface in there messed up. 在这里删除LeaderboardState接口,然后进入LeaderBoardConfiguration,当我在其中拥有接口时,情况就混乱了。

I suppose you have to send the object instead of array: 我想您必须发送对象而不是数组:

this.onLeaderboardStateUpdate(leaderboardInfo[0]); 
// [0] will extract the object inside array.-^^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM