【问题标题】:Can't find variable when adding data to Flatlist from json in React-Native在 React-Native 中从 json 向 Flatlist 添加数据时找不到变量
【发布时间】:2020-11-30 14:39:20
【问题描述】:

我是原生反应的新手,所以请善待!我正在尝试使用 JSON 填充平面列表。

下面是我的 JSON 数据

{
   "h1":{
      "baseprice":899,
      "description":"Upto Waist length Hair",
      "imageUrl":"https://i.imgur.com/0IgYzAv.jpg'",
      "price":799,
      "time":"25 min",
      "title":"Nourishing Hair Spa",
      "type":"Service"
   },
   "h2":{
      "baseprice":899,
      "description":"Touch Up of length less than 4 inches",
      "imageUrl":"https://i.imgur.com/q7ts4PZ.jpg",
      "price":799,
      "time":"45 min",
      "title":"INOA Root Touch Up",
      "type":"Service"
   }
}

这是我用来将 JSON 数据推送到我的 Flatlist 的代码

export default class Office extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: [],
    };
  }

  componentDidMount() {
    return fetch("https://stylmate1.firebaseio.com/hair.json")
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
        console.log(dataSource);
      })
      .catch((error) => {
        console.error(error);
      });
  }
  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, paddingTop: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.dataSource}
          renderItem={(item) => <Text>{item.title}</Text>}
        />
      </View>
    );
  }
}

我一刷新应用程序就会收到错误消息 找不到变量:数据源 但是如果我 console.log(responseJson);然后我得到完整的 JSON 对象。

我不知道我在这里做错了什么。请帮我解决这个问题。

【问题讨论】:

  • h1、h2 对你来说重要吗?

标签: arrays json react-native react-native-flatlist


【解决方案1】:

您的 FlatList 应该如下所示:


return (
      <View style={styles.container}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item[1].title}</Text>}
        />
      </View>
    );

您必须解构 item 才能使用它。

输出:

工作示例代码:

import React, { useState, useEffect } from 'react';
import { Text, View, FlatList, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

export default function App() {
  const [dataSource, setData] = useState([]);
  useEffect(() => {
    fetch('https://stylmate1.firebaseio.com/hair.json')
      .then((response) => response.json())
      .then((responseJson) => {
        setData(responseJson);
        console.log(responseJson);
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);
  return (
    <View style={styles.container}>
      {dataSource ? (
        <FlatList
          data={Object.entries(dataSource)}
          renderItem={({ item }) => (
            <View style={{ padding: 10 }}>
              <Card>
                <Text style={styles.paragraph}>{item[1].title}</Text>
              </Card>
            </View>
          )}
        />
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Expo Snack Live Demo

【讨论】:

  • 代码已经更新为从 url 获取它
  • 是的,先生!非常感谢,你是天赐之物。
  • 很高兴有帮助,编码愉快。
  • 您好 Ketan,我只想提醒您,现在我收到“JSON 无法对未安装的组件执行 React 状态更新”错误。您能否建议如何解决此问题。在这里查看:link
【解决方案2】:

发生错误是因为您尝试记录错误的数据源,它应该是 this.state.dataSource。

console.log(dataSource);

改成

console.log(this.state.dataSource);

在你的 .then() 块中

【讨论】:

  • 谢谢您,先生。我的平面列表也没有渲染。它是空白的。
  • 问题在于 renderItem= {({item})=> your components} 中的解构
  • 可能会有帮助
【解决方案3】:

首先,

console.log(dataSource);

应该改为

console.log(this.state.dataSource);

但是,您可能无法获得正确的 console.log,因为设置状态是异步的。使用 responseJson 获得更好、更准确的答案

其次,flatList 需要一个对象数组结构,需要使用以下方法进行转换。我将您的“h1”和“h2”移动到对象中并将它们标记为键。

const original = {
   "h1":{
      "baseprice":899,
      "description":"Upto Waist length Hair",
      "imageUrl":"https://i.imgur.com/0IgYzAv.jpg'",
      "price":799,
      "time":"25 min",
      "title":"Nourishing Hair Spa",
      "type":"Service"
   },
   "h2":{
      "baseprice":899,
      "description":"Touch Up of length less than 4 inches",
      "imageUrl":"https://i.imgur.com/q7ts4PZ.jpg",
      "price":799,
      "time":"45 min",
      "title":"INOA Root Touch Up",
      "type":"Service"
   }
}

const newArray = Object.keys(original).map( key => ({...original[key], key }))

console.log(newArray)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2021-12-29
    相关资源
    最近更新 更多