【发布时间】:2019-02-05 19:31:41
【问题描述】:
我正在使用 axios 从 api 获取数据。 我的路由器是:
<Route exact path='/device/:id/update' render={(props) => <DeviceTypeUpdate {...props} />} />
我的 componentDidMount 是:
componentDidMount() {
console.log('------this.props.match.id----', this.props.match.params.id)
const ied = this.props.match.params.id
axios({
url: 'http://127.0.0.1:8000/api/devicetypeget/'+ied,
method: 'get',
headers: {
'Content-Type' : 'application/json'
}
})
.then(function(response) {
return response;
})
.then(function (devicetype) {
this.setState(function () {
return {devicetype: devicetype, isLoaded: true}
})
}.bind(this))
.catch(function (error) {
this.setState(function () {
return {error, isLoaded: true}
})
}.bind(this))
}
在我的渲染方法中,我尝试在控制台中记录数据,如下所示:
const {error, isLoaded, devicetype} = this.state
console.log('----error----', error);
console.log('----devicetype in render----', devicetype.data);
devicetype.data 打印出其中包含嵌套数据的 JSON 对象,如下所示:
assignment_date: {$date: 1548744545634}
device_elements: {type: "switch", name: "board", state: "some state"}
dev_stage: "PLANNING"
type_description: "some description"
type_name: "Board"
_id: 1
当我使用 console.log(devicetype.data.device_elements) 或任何其他属性时
它会抛出错误"TypeError: Cannot read property 'type_name' of undefined"
我做错了什么。请帮帮我
【问题讨论】:
-
this.state.devicetype的初始值是多少?我的猜测是您的组件在设置this.state.devicetype.data以响应 axios 调用之前渲染,因此初始渲染试图访问一个不存在的对象(尚)。 -
@christian 我的 this.state.devicetype 的初始值为 {} 空对象。
-
如果我的组件在“this.state.devicetype.data”设置为 axios 调用之前渲染。那我该如何解决呢。
-
这取决于您希望您的 UI 如何处理这种情况。通常这种行为是可取的,因为它使您有机会在加载数据时显示“正在加载...”消息,否则在加载数据之前您的组件不会呈现。您可以在
render()函数中添加 if 语句来处理尚未加载数据的情况。在伪代码中:if (dataIsNotLoaded) displayLoadingMessage else displayData
标签: javascript json reactjs