React Native渲染嵌套的Json

时间:2018-07-04 13:51:47

标签: json reactjs nested native

在加载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"
  }
}

以下结果:

  1. {this.state.weatherList.ts}的工作原理:1530703572
  2. {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)=> )进行了尝试,但没有成功。

谢谢!

1 个答案:

答案 0 :(得分:0)

在设置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>
    );
  }
}