我正在尝试制作一个简单的新闻应用程序以学习反应。不断收到我不明白的错误。为什么应用程序可以与JSON占位符api一起正常工作。但是现在它显示错误props.stories.map不是一个函数。
这是我的代码。
class App extends React.Component {
constructor() {
super()
this.state = {
stories: [],
}
}
componentDidMount() {
fetch(`https://newsapi.org/v2/top-headlines?country=gb&apiKey=${API_KEY}`)
.then(res => res.json()
.then(data => this.setState({stories: data}))
)
}
render(){
const { stories } = this.state
return (
<div className="App">
<NewsList stories={stories} />
</div>
);
}
}
import Story from './Story'
import styled from 'styled-components'
const NewsList = props => {
return(
<NewsListWrapper>
{
props.stories.map(story => (
<Story story={story} />
)
)
}
</NewsListWrapper>
)
}
import React from 'react';
import styled from 'styled-components';
export const Story = props => (
<StoryWrapper>
<h2>{props.story.title}</h2>
<p>{props.story.author}</p>
<p>{props.story.articles}</p>
</StoryWrapper>
)
我有console.log的api响应,并且可以很好地接收数据。只是当我使用其他api响应时。我只是为这篇文章隐藏了我的api_key,所以这不是问题。
感谢您的任何建议。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
遇到错误 "props.stories.map不是一个函数" 通常意味着你尝试对一个非数组类型的对象执行.map()
操作。根据你的代码片段,问题可能出在以下几个方面:
确保stories
是一个数组:首先确认从API获取的数据确实被解析为一个数组。新闻API通常会返回一个包含多个文章对象的数组,但有时如果请求失败或路径错误,可能会返回一个错误对象或空对象,而不是预期的数组。
检查API响应和数据处理:你需要在componentDidMount
中正确处理API响应。确保你正确地解析了JSON响应,并且将结果赋值给了this.state.stories
。这里是一个基本的示例,展示了如何在fetch成功后更新state:
componentDidMount() {
fetch(`https://newsapi.org/v2/top-headlines?country=gb&apiKey=YOUR_API_KEY`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
this.setState({ stories: data.articles }); // 假设API返回的对象中,新闻条目在articles字段里
})
.catch(error => console.error('There was a problem with the fetch operation:', error));
}
请记得替换YOUR_API_KEY
为你的实际News API密钥。
检查传递给组件的props:如果你的组件是从其他地方接收stories
作为props,确保传递给它的确实是数组类型。如果这个组件是直接使用state中的stories
,那么问题应该在于上述数据获取或处理过程。
渲染逻辑:在你的组件的render方法中,确保在调用.map()
之前检查this.state.stories
是否存在且为数组。可以添加一个简单的条件渲染来避免错误:
render() {
const { stories } = this.state;
if (!Array.isArray(stories)) {
return <div>Loading...</div>; // 或者显示错误信息
}
return (
<div>
{stories.map(story => (
// 这里是你的渲染逻辑
))}
</div>
);
}
通过以上步骤,你应该能够定位并解决"props.stories.map不是一个函数"的问题。如果问题仍然存在,可能需要更详细地检查你的API调用设置、网络环境或者React组件的其他部分。