React .map使用Fetch API返回undefined

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

我希望我的React render方法以类似于Postman的方式从API返回对象。例如:

{
  "meta": {
    "count": 807,
    "countReturned": 10,
    "requestTime": 1552524395,
    "responseTime": 1552524395,
    "responseMs": 7
  },
  "data": [
     {
        "type": "breeds",
        "id": "1",
        "attributes": {
            "name": "Abyssinian"
        },
        "relationships": {
            "species": {
                "data": [
                    {
                        "type": "species",
                        "id": "3"
                    }
                ]
            }
        },
        "meta": []
    },

但是我在使用.map生成我想要的对象时遇到了麻烦。这是我的代码:

class Results extends Component {
constructor() {
    super();
    this.state = {
        animals: [],
    };
}

componentDidMount() {
    var url = "https://test1-api.rescuegroups.org/v5/public/animals/breeds?fields[breeds]=name&fields[species]=singular,plural,youngSingular,youngPlural&include=species&options=meta&limit=10";
    const API_KEY = process.env.REACT_APP_API_KEY;

    fetch(url, {
        method: 'GET',
        headers: {
            Authorization: API_KEY,
            'Content-Type': 'application/json'}
    })
    .then(response => response.json())
    .then(data => this.setState({animals: data.results }))
}

render() {
    return (

        <div>
            {this.state.animals.map(animal => <div>{animal.results}</div>)}
        </div>

    )
}
}

export default Results;

任何提示表示赞赏!

javascript reactjs fetch-api array.prototype.map
3个回答
1
投票

名为“data”的回调方法的参数并不意味着它是响应数据的data属性。

我认为回调应该是

...
.then(response => response.json())
.then(response => this.setState({animals: response.data}))

<div>
  {this.state.animals.map(animal => <div>{animal.type}</div>)}
</div>

1
投票

如果您确定所获得的JSON数据是正确的,那么您可以使用以下代码遍历该对象。

 Object.keys(this.state.animals).map((key) => {
    return <div value={key}>{ this.state.animals[key] }</div>
});

1
投票

我认为这会使您感到困惑,因为您的命名惯例略有混乱。你的componentDidMount函数需要看如下:

componentDidMount() {
    var url = "https://test1-api.rescuegroups.org/v5/public/animals/breeds?fields[breeds]=name&fields[species]=singular,plural,youngSingular,youngPlural&include=species&options=meta&limit=10";
    const API_KEY = process.env.REACT_APP_API_KEY;

    fetch(url, {
        method: 'GET',
        headers: {
            Authorization: API_KEY,
            'Content-Type': 'application/json'}
    })
    .then(response => response.json())
    .then(json => this.setState({animals: json.data }))
}

您需要从响应中提取data密钥,当前命名时,data.data将为animals

在渲染功能中,您将使用您所在州的render() { console.log(this.state); return ( <div> {this.state.animals.map(animal => <div>{animal.attributes.name}</div>)} </div> ) } 。如果您想要动物的名称,您将使用以下内容:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.