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

问题描述 投票:2回答:3

我正在做一个反应原生的单页应用程序。我想在列表视图中显示获取响应。为了访问响应数组,我使用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;

我做错了什么?

javascript arrays json react-native
3个回答
3
投票

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

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

因为您只从您的回复数据中考虑neighbourProfile


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 => {...});

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


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} />
      );
      
    }
© www.soinside.com 2019 - 2024. All rights reserved.