【问题标题】:ReactJs - API Feed Error - cannot read property of map undefinedReactJs - API Feed 错误 - 无法读取未定义的地图属性
【发布时间】:2018-09-10 10:41:36
【问题描述】:

我希望你能帮助我。我正在尝试使用 axios/ReactJs 将一个简单的 TFL 管 API 插入到我的网页中。

集成非常简单。我正在使用 app.js,然后是一个功能组件,我将在其中循环/映射数据并通过<li>s 将我需要的信息提取到我的网页中。

但是,我的<Frame /> 组件中不断出现以下错误:

app.js:29827 Uncaught TypeError: Cannot read property 'map' of 
undefined at Frame (app.js:29827)

这不喜欢我在“提要”上的映射方式。我不确定我错过了什么,因为此代码通常适用于简单的 API 集成。

这是 app.js

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import Frame from './components/Frame';
import 'bulma';


class App extends React.Component {

  constructor() {
    super();
    console.log('CONSTRUCTOR');

    this.state = {
      feed: []
    };
  }

 //pull through the TFL data
 componentDidMount() {
  console.log('tfl feed');
   axios.get('https://api.tfl.gov.uk/Line/Mode/tube/Status?detail=true&app_id=IVEREMOVEDAPIID&app_key=IVEREMOVEDAPIKEY')
  //response
  .then(res => {
    console.log(res);
    console.log(res.data);
    console.log(res.data[0].name);
    this.setState(
      { feed: res.data });
  });
  }


  render() {
    return(
      <section>
        <div>
          <h1>Tube Status</h1>
          <Frame />
        </div>
      </section>
     );
    }
   }


ReactDOM.render(
  <App />,
  document.getElementById('root')
);

这是&lt;Frame /&gt; 模块,我正在其中进行映射:

import React from 'react';

const Frame = ({feed}) => {

return (

<section>
  <div className="columns is-multiline">
    <ul>
      {feed.map((tube, i) => <li className="column is-one-quarter" key={i}>
        {tube.name}
      </li>)}
    </ul>
  </div>
</section>
  );
};

export default Frame;

任何指针,都会很棒!

【问题讨论】:

    标签: reactjs api axios array.prototype.map


    【解决方案1】:

    feed undefined 因为你没有将道具传递给组件。查看您的渲染方法。

    只需将饲料和平状态作为道具传递给Frame

    render() {
     return(
       <section>
         <div>
           <h1>Tube Status</h1>
           <Frame feed={this.state.feed}/>
         </div>
       </section>
      );
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 2020-09-14
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2021-11-17
      • 2021-12-31
      相关资源
      最近更新 更多