我正在尝试解析来 self 的 reactjs 网络应用程序的嵌套 json 请求。
下面是我从请求中收到的 json。
response.data
{
"total": 2,
"offset": 1,
"limit": 987,
"staging": [
{
"id": 101,
"name": "Test Stage"
},
{
"id": 102,
"name": "Dev Stage"
},
{
"id": 103,
"name": "Prod Stage"
}
]
}
我需要解析“staging”并在浏览器屏幕上显示结果。
下面是我要解析的代码。但是,它抛出错误 (SyntaxError: Unexpected token o in JSON at position 1)
。
export default class ItemLister extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios
.get('https://xxx.yyy.zzz/xyz/zyx/', {
headers: {
'authorization':'Bearer XXXXXXXXX',
'X-Api-Key': 'XXXXXXXXXXXXXX',
},
withCredentials: true
})
.then(response => {
console.log(response.data) // it gets the correct response and printing in logs
const persons = response.data;
this.setState({ persons });
})
.catch (err => {
console.log("error")
});
}
render() {
return <ul>{this.state.persons.map(person => <li>{person.name}</li>)}</ul>
}
}
ReactDOM.render(<ItemLister />, document.getElementById('root'))
registerServiceWorker()
我找不到解决办法。谁能指导我解析这样的json是否正确,以及如何获取解析结果并显示在屏幕上?
最佳答案
发生错误是因为您正在尝试解析 Object
而不是 String
。只需跳过 JSON.parse
并将 result
设置为 response.data
:
.then(response => {
console.log(response.data) // it gets the correct response and printing in logs
this.setState({ result: response.data });
})
在你的 render
中:
render() {
return (
<ul>
{ this.state.result &&
this.state.result.staging &&
this.state.result.staging.map(person => <li>{person.name}</li>)
}
</ul>
);
}
关于javascript - 从 ReactJS 应用程序解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53067902/