来自 json 对象的 setState 给出未定义的 [React]
setState from json object gives undefined [React]
所以我遇到了这个问题,我从后端得到响应并将其解析为 json 然后像这样调用我的设置函数
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 给了我这个回复
到目前为止,它是我想用来设置状态的 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 接口并进入 LeaderBoardConfiguration,当我在那里的接口搞砸了。
我想你必须发送对象而不是数组:
this.onLeaderboardStateUpdate(leaderboardInfo[0]);
// [0] will extract the object inside array.-^^^
所以我遇到了这个问题,我从后端得到响应并将其解析为 json 然后像这样调用我的设置函数
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 给了我这个回复
到目前为止,它是我想用来设置状态的 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 接口并进入 LeaderBoardConfiguration,当我在那里的接口搞砸了。
我想你必须发送对象而不是数组:
this.onLeaderboardStateUpdate(leaderboardInfo[0]);
// [0] will extract the object inside array.-^^^