【问题标题】:array undefine after a setState and an API resultsetState 和 API 结果后未定义的数组
【发布时间】:2020-03-29 21:49:34
【问题描述】:

我从 react-native 开始。

我正在尝试创建一个 ImageGallery。 拥有此 Gallery 的步骤之一是使用 API 的结果在状态下启动数组。

  1. 我在名为“images”的状态上启动了一个 void 数组
  2. 我通过 console.log 调用 API -->,我看到的结果正确
  3. 我想设置我的数组“images”
  4. 我想读取我的数组“图像”

这是我的代码

import React from 'react';
import {
    View,
    Image,
    FlatList
} from 'react-native';

export default class TestGallery extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        error: null,
        images: []
    };
}

componentDidMount() {
    fetch("*************************************")
        .then(res => res.json())
        .then(res => console.log(res))
        .then((result) => {
                this.setState({
                    images: result.images
                });
            },
            (error) => {
                this.setState({
                    error
                });
            }
        )
}

render() {
    console.log('Step 3 : RENDER')

    console.log(this.state.images)

    return (
        <View style={{ height: 200, width: 200 }}>
            <FlatList
                data={this.state.images}
                renderItem={({ item }) => (
                    <Image
                        style={{ height: 200, width: 200, backgroundColor: 'red' }}
                        source={this.state.images}
                    />
                )}
            />
        </View>

    )
}
}

控制台:

Step 3 : RENDER
Array []
Array [
  "photo(3).jpg",
  "photo(7).jpg",
  "photo(2).jpg",
  "photo(8).jpg",
  "photo(14).jpg",
  "photo(12).jpg",
  "photo(6).jpg",
  "photo(15).jpg",
  "photo(10).jpg",
  "photo(9).jpg",
  "photo(5).jpg",
  "photo(1).jpg",
  "photo(11).jpg",
  "photo(13).jpg",
  "photo(4).jpg",
]

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'result.images')]

有人可以帮助我吗? 为什么我不能 setState 我的数组“Images”

【问题讨论】:

    标签: react-native state setstate


    【解决方案1】:
    1. 正如您在 console.log 中所见,您的响应已经是一组图像(名称而不是看起来的 URL)。您期待一个带有 images 键的对象。那么,您将不得不为此调整您的 API 端点。要将结果数组放入您的状态,您可以执行以下操作。
    fetch(...)
    .then(res => res.json())
    .then(json => {
      console.log(json)
      this.setState({images: json})
    })
    
    1. 您的图像不会与此代码一起显示,因为您得到的是图像名称。当这些图像保存在您的 RN 项目中时,您必须使用 require 作为具有正确图像路径的图像源。但我很确定你想从uri 进行渲染,所以你必须使用uri 作为图像源,并带有正确的图像URL。

    2. 您需要将item 中的renderItem 函数用于图像源,因为这将是this.state.images 的一项。您将保存在this.state.images 中的整个数组传递给图像源。

    您确实应该更仔细地阅读文档。 图片:https://reactnative.dev/docs/image 平面列表:https://reactnative.dev/docs/flatlist.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      相关资源
      最近更新 更多