我在 fetch()
中得到以下响应
{
"errorCode": "00",
"errorMsg": "success",
"roleList": [
{
"role_id": 900,
"roleDescription": "Role_I"
},
{
"role_id": 901,
"roleDescription": "Role_II"
}
]
}
现在我需要获取 roleDescription 并将其呈现在 中,因此我尝试遍历 JSON 并将 roleDescription 存储在状态数组中。
下面是为此编写的方法:
getroles(e) {
fetch('http://xyz', {
method: 'POST',
body: JSON.stringify({
"role_id": this.props.location.state.role_id
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(`response of getroles: `, responseJson)
if (responseJson.errorCode === '00') {
this.setState({roleList : JSON.stringify(responseJson.roleList)});
let temp = [];
for (var i=0; i < JSON.stringify(responseJson.roleList).length; i++) {
temp.push(JSON.stringify(responseJson.roleList[i].roleDescription))
}
}
else {
alert("Error Fetching roles" + responseJson.errorMsg);
}
})
.catch((error) => {
console.error(error);
});
}
但我收到错误
Cannot read property 'roleDescription' of undefined
上线temp.push
我对 react 还很陌生,所以我不太确定我的方法是否正确。请帮忙。
最佳答案
您根本不应该使用 JSON.stringify
方法:
getroles(e) {
fetch('http://xyz', {
method: 'POST',
body: JSON.stringify({
"role_id": this.props.location.state.role_id
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(`response of getroles: `, responseJson)
if (responseJson.errorCode === '00') {
this.setState({roleList : responseJson.roleList});
let temp = [];
for (var i = 0; i < responseJson.roleList.length; i++) {
temp.push(responseJson.roleList[i].roleDescription);
}
}
else {
alert("Error Fetching roles" + responseJson.errorMsg);
}
})
.catch((error) => {
console.error(error);
});
}
我想知道如果您查询单个角色,为什么会收到角色列表?
此外,如果您决定将 temp
变量设置为状态,最好同时设置变量 temp
和 roleList
同时。
稍后编辑:您无需设置任何临时变量即可使用角色描述填充选择器。
getroles(e) {
fetch('http://xyz', {
method: 'POST',
body: JSON.stringify({
"role_id": this.props.location.state.role_id
})
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.errorCode === '00') {
this.setState({roleList : responseJson.roleList});
}
else {
alert("Error Fetching roles" + responseJson.errorMsg);
}
})
.catch((error) => {
console.error(error);
});
}
当你渲染选择器时,你应该有类似的内容:
<select onChange={(event) => alert('Role description for role having id ' + event.value + ' has been selected')}>
<option value="">Please choose a description</option>
{this.state.roleList.map((role) => {
return (
<option key={role.role_id} value={role.role_id}>
{role.roleDescription}
</option>
);
})}
</select>
关于json - React中嵌套JSON解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54648234/