React Native类型错误:this.props.data.map不是函数

时间:2017-12-20 05:00:33

标签: javascript arrays json react-native

我正在做反应原生的单页应用程序。我想在列表视图中显示获取响应。为了使用map方法访问响应数组,但是出现了上述错误。我服务器的响应看起来像这样

{
  "responseHeader": {
    "type": "314",
    "status": "200",
    "message": "Successfully found the profile"
  },
  "neighbourProfile": [{
    "no_of_mutual_friends": "0",
    "username": "Amith Issac",
  },
  {
    "no_of_mutual_friends": "0",
    "username": "Liz",
  }]
}

如何在这里使用map方法?我的app.js如下

app.js

import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import Neighbour from './src/components/Neighbour';

 class App extends Component {
    state = { neighbours: [] };
    componentWillMount(){
        const myArray = 
        {"requestHeader":
        {
            "personal_id": "122334",
            "type":"314"
        }
        }
        fetch(" https://xxxxx",{
            method: 'POST',
            headers:{
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
           body: JSON.stringify(myArray)
        })
        .then((response) => response.json())
        .then((responseData) =>this.setState({neighbours: responseData}));

    }
    renderNeighbour(){
        return this.state.neighbours.map(neighbours =>
        <Neighbour key ={neighbours.username} neighbours={neighbours}/>
        );
    }
  render() {
    return (
      <ScrollView>
      {this.renderNeighbour()}
      </ScrollView>
    );
  }
}
export default App;

我做错了什么?

3 个答案:

答案 0 :(得分:3)

对于您的情况,您必须使用responseData.neighbourProfile才能使其正常工作:

.then((responseData) =>this.setState({neighbours: responseData.neighbourProfile}));

由于您只从响应数据中考虑neighbourProfile

答案 1 :(得分:2)

根据this answer,您需要执行以下操作来映射Javascript Object(如Python字典)。

Object.keys(someObject).map(function(item)...
Object.keys(someObject).forEach(function(item)...;

// ES way
Object.keys(data).map(item => {...});
Object.keys(data).forEach(item => {...});

这是因为只有Array在Javascript中有map方法; Object没有这种方法。

答案 2 :(得分:0)

responseData应该只是一个数组..

类似这样的事情: -

    responseData = [
      {
        "no_of_mutual_friends": "0",
        "username": "Amith Issac",
      },
      {
        "no_of_mutual_friends": "0",
        "username": "Liz",
      }
    ];

虽然地图有这样的东西..通常我们不能直接使用this.state来映射,因为它会成为别的东西..所以,如果你分配一个变量并从状态中获取值,那就更好了。

renderNeighbour(){
      
      //this one
      const { neighbours } = this.state;
      
      //or this one
      let neighbours = this.state.neighbours;
      
      return neighbours.map((data) =>
        <Neighbour key={data.username} neighbours={neighbours} />
      );
      
    }