【发布时间】:2020-12-12 15:45:48
【问题描述】:
我从服务器获得了一个数组。 这是数组:
[{"body":"one"},{"body":"two"},{"body":"three"}]
在 Home2 组件中:
import React, { Component } from 'react';
class Home2 extends Component {
constructor() {
super()
this.state={
status:''
}
}
componentDidMount(){
let store = JSON.parse(localStorage.getItem('login'))
var url = 'http://127.0.0.1:8000/myapi/allpost/?format=json'
fetch(url,{
method:'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token '+store.token
}
})
.then(res=>res.json().then(result=>{
this.setState({status: result})
}))
}
render() {
var list = this.state.status
var object = list[0]
console.log(object['body'])// <-- what is the problem?
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
export default Home2;
代码运行时显示TypeError: undefined is not an object (evalating 'object['body']')
问题出在哪里? 如何 console.log 'one' ?
【问题讨论】:
-
当你 console.log(object) 它记录什么?如果它记录 {"body":"one"} 那么你可以调用 object.body。但我认为它会记录未定义
-
n.b:
render被称为之前componentDidMount(参见:reactjs.org/docs/react-component.html#mounting)
标签: javascript reactjs