gpt4 book ai didi

javascript - json 对象中的 setState 给出未定义的 [React]

转载 作者:行者123 更新时间:2023-12-01 01:31:11 26 4
gpt4 key购买 nike

所以我遇到了这个问题,我从后端得到响应,并将其解析为 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`);
}

console.log 给了我这个响应

enter image description here

到目前为止,我想用 LeaderboardConfig 来设置状态,效果很好。

我的setState函数只是一个基本函数

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

我的状态看起来像这样

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

但由于某种原因,这给出了未定义,因此似乎无法从我拥有的 json 对象中设置状态

供您引用,leaderboardState 是一个如下所示的界面。

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

Jai 所说的让我解决了这个问题,我必须将 try catch 更改为此

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`);
}

删除此处的 LeaderboardState 接口(interface)并进入 LeaderBoardConfiguration,当我在那里的接口(interface)困惑时。

最佳答案

我想你必须发送对象而不是数组:

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

关于javascript - json 对象中的 setState 给出未定义的 [React],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53259676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com