开发者社区 问答 正文

reactJS-props.stories.map不是函数吗?

我正在尝试制作一个简单的新闻应用程序以学习反应。不断收到我不明白的错误。为什么应用程序可以与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,所以这不是问题。

感谢您的任何建议。

展开
收起
被纵养的懒猫 2019-09-25 16:00:58 339 分享 版权
阿里云 AI 助理回答

遇到错误 "props.stories.map不是一个函数" 通常意味着你尝试对一个非数组类型的对象执行.map()操作。根据你的代码片段,问题可能出在以下几个方面:

  1. 确保stories是一个数组:首先确认从API获取的数据确实被解析为一个数组。新闻API通常会返回一个包含多个文章对象的数组,但有时如果请求失败或路径错误,可能会返回一个错误对象或空对象,而不是预期的数组。

  2. 检查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密钥。

  1. 检查传递给组件的props:如果你的组件是从其他地方接收stories作为props,确保传递给它的确实是数组类型。如果这个组件是直接使用state中的stories,那么问题应该在于上述数据获取或处理过程。

  2. 渲染逻辑:在你的组件的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组件的其他部分。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答标签:
问答地址: