[英]Mapping a text response in javascript
Initializing the state初始化 state
this.state = {
apiResponse : []
}
setting the state to response from api inside componentDidmount将 state 设置为来自 api 内部 componentDidmount 的响应
this.setState({
apiResponse: response
})
"response" looks like “响应”看起来像
{polyinfo: "{"name": "hello1"}"}
{polyinfo: "{"name": "hello2"}"}
I need to get the value of name我需要获取 name 的值
Things i tried我尝试过的事情
list = () => {
const polyInfo = JSON.parse(this.state.apiResponseJson);
return polyInfo.map(element => {
console.log(element.name);
// console.log(element.polyinfo.name);
});
}; };
it seems like you forgot to add a comma at the end of the first line in好像你忘了在第一行的末尾添加一个逗号
{polyinfo: "{"name": "hello1"}"}
{polyinfo: "{"name": "hello2"}"}
but assuming that this was typed as a valid array, the correct way to access name here would be但假设这是一个有效的数组,这里访问名称的正确方法是
const parsedContainer = JSON.parse(this.state.apiResponse[i].polyinfo) //where "i" is the //array index
console.log(parsedContainer.name) //logging the name to the console
this works because we are parsing the string type json from polyinfo and parsing it into json that javascript can read and then we are using that parsed json to read the name property. this works because we are parsing the string type json from polyinfo and parsing it into json that javascript can read and then we are using that parsed json to read the name property.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.