gpt4 book ai didi

javascript - react 应用程序 : Undefined value after fetch

转载 作者:行者123 更新时间:2023-11-29 16:35:28 24 4
gpt4 key购买 nike

我有以下代码,我从 Twitter API 提要中获取数据。我使用回调函数并将值设置为我的状态属性。当我在渲染中使用它来控制台并查看值时,它会显示

"Cannot read property 'created_at' of undefined".

我认为它正在尝试在可用之前获取。我不知道在这里做什么。有人可以帮忙吗?当我使用 console.log(this.state.twitterfeed.techcrunch[0]) 时,我没有收到任何错误。

我得到了对象

但是当我使用 console.log(this.state.twitterfeed.techcrunch[0].created_at) 时我得到了错误

    class Columns extends Component {
constructor() {
super();
this.state = {
twitterfeed: {
techcrunch: [],
laughingsquid: [],
appdirect: []
}
};
}
updateTwitterFeed = (data, user) => {
var twitterfeed = { ...this.state.twitterfeed };
if (user === "appdirect") {
twitterfeed.appdirect = data;
} else if (user === "laughingsquid") {
twitterfeed.laughingsquid = data;
} else {
twitterfeed.techcrunch = data;
}
this.setState({ twitterfeed });
};

componentDidMount() {
fetch(
"http://localhost:7890/1.1/statuses/user_timeline.json?count=30&screen_name=techcrunch"
)
.then(response => response.json())
.then(data => this.updateTwitterFeed(data, "techcrunch"));
fetch(
"http://localhost:7890/1.1/statuses/user_timeline.json?count=30&screen_name=laughingsquid"
)
.then(response => response.json())
.then(data => this.updateTwitterFeed(data, "laughingsquid"));
fetch(
"http://localhost:7890/1.1/statuses/user_timeline.json?count=30&screen_name=appdirect"
)
.then(response => response.json())
.then(data => this.updateTwitterFeed(data, "appdirect"));
}

render() {
return (
<div className="container mx-0">
<div className="row">
<div className="col-4 col-md-4">
{console.log(this.state.twitterfeed.techcrunch[0].created_at)}
<Column tweet={this.state.twitterfeed.techcrunch} />
</div>
</div>
</div>
);
}
}

最佳答案

this.state.twitterfeed.techcrunch[0] 将在您的提取完成之前未定义,因此尝试访问 created_at会引起你的错误。

例如,您可以呈现 null 直到 techcrunch 数组在请求后被填充。

class Columns extends Component {
// ...

render() {
const { techcrunch } = this.state.twitterfeed;

if (techcrunch.length === 0) {
return null;
}

return (
<div className="container mx-0">
<div className="row">
<div className="col-4 col-md-4">
<Column tweet={techcrunch} />
</div>
</div>
</div>
);
}
}

关于javascript - react 应用程序 : Undefined value after fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51605256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com