无法从我的ReactJs站点中的服务器获取数据



从JSON提取数据时出现未定义的数据类型错误

我搜索了很多地方,但没有得到合适的答案

import SavedData from "./SavedData";
export default class Saved extends React.Component {
constructor() {
super();
this.state = {
loading: true,
datas: [],
};
}
async componentDidMount() {
const url = "https://todo-list-site.herokuapp.com/todo-data";
const response = await fetch(url);
const todoData = response.json().then((res) => {
this.setState({ datas: res });
});
}
render() {
console.log(this.state.datas[0].description);   //not able to get data
return (
<div>
{/* {this.state.datas.map((items) => (
<SavedData
key={items.countTodo}
title={items.title}
desc={items.desc}
/>
))} */}
</div>
);
}
}

有人帮我,这样我就可以继续

正如Dave Newton在评论中指出的那样,渲染是在请求完成之前触发的。这很正常,你只需要正确处理它。

如果您看到这个代码沙盒的控制台日志,您可以看到最初this.state.datas只是一个空数组[],因此任何访问this.state.datas[0].description的尝试都将是undefined。只有在请求完成时更新状态后,日志才会显示检索到的数据——这是因为根据ReactComponent的装载生命周期,render()componentDidMount()之前被调用,请求也是异步的。

这是非常常见的,甚至官方React文档建议在componentDidMount()中进行HTTP调用。文档还提供了一个处理此问题的示例。

import SavedData from "./SavedData";
export default class Saved extends React.Component {
constructor() {
super();
this.state = {
loading: true,  // we initially set this to true
datas: [],
};
}
async componentDidMount() {
const url = "https://todo-list-site.herokuapp.com/todo-data";
const response = await fetch(url);
const todoData = response.json().then((res) => {
this.setState({
datas: res,
loading: false  // when the request is complete, we set this to false
});
});
}
render() {
if (this.state.loading) {
// during the first render, loading will be true and we
// can return a loading message or a spinner
return (
<div>Loading...</div>
);
}
// when render is called after the state update, loading will be false
// and this.state.datas will have the fetched data
console.log(this.state.datas[0].description);
return (
<div>
{this.state.datas.map((items) => (
<SavedData
key={items.countTodo}
title={items.title}
desc={items.desc}
/>
))}
</div>
);
}
}

您的数据状态最初是一个空数组,直到您的componentDidMount激发并设置状态。因此,在设置状态之前,您的控制台日志将是未定义的。为了解决此问题,您必须等待this.state.datas[0]为true,然后才能访问数组中的第一个对象描述。以下代码似乎按预期工作

import React from "react";
export default class Saved extends React.Component {
constructor() {
super();
this.state = {
loading: true,
datas: []
};
}
async componentDidMount() {
const url = "https://todo-list-site.herokuapp.com/todo-data";
const response = await fetch(url);
response.json().then((res) => {
this.setState({ datas: res });
});
}
render() {
console.log(this.state.datas[0] && this.state.datas[0].description);
return (
<div>
{this.state.datas.map((items, i) => (
<div key={i}>
<div> title={items.title}</div>
<div> desc={items.description}</div>
</div>
))}
</div>
);
}
}

最新更新