反应本机呈现嵌套Json

人气:920 发布:2022-10-16 标签: json nested native reactjs

问题描述

加载JSON对象并将其添加到this.State后,我无法访问第一个级别以下的级别。给定此JSON文件:

{
  "ts": 1530703572,
  "trend": {
    "val": 0,
    "text": "gleichbleibend"
  },
  "baro": 1011.3453734999999,
  "temp": {
    "out": {
      "f": 85.9,
      "c": 29.9
    }
  },
  "hum": {
    "out": 28
  },
  "wind": {
    "speed": {
      "mph": 2,
      "kmh": 3.2
    },
    "avg": {
      "mph": 3,
      "kmh": 4.8
    },
    "dir": {
      "deg": 192,
      "text": "SSW"
    }
  },
  "rain": {
    "rate": 0,
    "storm": 0,
    "day": 0,
    "month": 0,
    "year": 451.358
  },
  "et": {
    "day": 88,
    "month": 81,
    "year": 1802
  },
  "forecast": {
    "val": 6,
    "rule": 45,
    "text": "Zunehmend wolkig bei gleichbleibender Temperatur."
  },
  "sun": {
    "uv": 6.2,
    "rad": 779,
    "rise": "4:27",
    "set": "20:35"
  }
}

以下结果:

{this.state.weatherList.ts}作品:1530703572 {this.state.weatherList.temp.out.c}"TypeError:未定义不是对象(求值:‘this.state.weatherList.temp.out’)

代码:

export default class Weather extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            weatherList: []
        }

        getPlannerData().then(data => {
            this.setState({
                weatherList: data
            })

        })
    }

        return (
            <ScrollView>
                <View>
                    <View>
                        <Text>{this.state.weatherList.temp.out.c}</Text>
                    </View>

                </View>
            </ScrollView>
        )
    }
}

async function getPlannerData() {
    let data = await fetchApi('url')
    return data
}

async function fetchApi(url) {
    try {
        let response = await fetch(url)
        let responseJson = await response.json()
        console.log(responseJson)
        return responseJson
    } catch (error) {
        console.error(error)
        return false
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 22
    },
    sectionHeader: {
        paddingTop: 2,
        paddingLeft: 10,
        paddingRight: 10,
        paddingBottom: 2,
        fontSize: 14,
        fontWeight: 'bold',
        backgroundColor: 'rgba(247,247,247,1.0)'
    },
    item: {
        padding: 10,
        fontSize: 18,
        height: 44
    }
})

问题是如何更改代码,以便可以访问"temp"之类的嵌套元素。

我用renderItem和{this.state.weaetherList.map((Item,i)=>尝试过,但没有成功。

提前谢谢!

推荐答案

在设置weatherList对象之前,任何超出对象级别的操作都将导致错误。this.state.weatherList.ts不会给出错误,因为它只是在您的请求完成前undefined

例如,您可以保留状态变量loading,并仅在您的请求完成后才呈现以解决此问题。

示例

class Weather extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: true,
      weatherList: {}
    };

    getPlannerData().then(data => {
      this.setState({
        loading: false,
        weatherList: data
      });
    });
  }

  render() {
    const { loading, weatherList } = this.state;

    if (loading) {
      return null;
    }

    return (
      <ScrollView>
        <View>
          <View>
            <Text>{weatherList.temp.out.c}</Text>
          </View>
        </View>
      </ScrollView>
    );
  }
}

237