【问题标题】:React Native render nested JsonReact Native 渲染嵌套的 Json
【发布时间】:2018-07-04 13:51:47
【问题描述】:

加载 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: Undefined is not an object (Evaluating: '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) => 没有成功。

提前致谢!

【问题讨论】:

    标签: json reactjs nested native


    【解决方案1】:

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

    【讨论】:

    • 我不得不将 loading: true 改为 false,现在它可以工作了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-06-25
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    相关资源
    最近更新 更多