【问题标题】:props showing empty array - React Native显示空数组的道具 - React Native
【发布时间】:2017-10-18 16:20:32
【问题描述】:

我正在自学 React。我有一些问题。我正在尝试将数据提取到另一个组件。在映射 JSON 数据后,我尝试setState。但它显示错误“setState is not a function”。

  1. 映射JSON数据后如何setState

    // Fetching data and passing JSON values to TabBarMenu component
    
    export default class App extends Component {
        state = {
          temp: [],
          description: [],
          time: []
        };
    
    _getFiveWeather = (lat, lng) => {    
        fetch(`http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lng}&APPID=${API_KEY}`)
            .then(response => response.json())
            .then(json => json.list.map(function(item) {
              return (
                <TabBarMenu key={item.dt_txt} time={item.dt_txt} description={item.weather.description} />
              );
            })
    }}
    

TabBarMenu.js 中,我试图将props(时间、描述)传递给_FirstRoute。当我执行console.log(this.props), 时,它显示的是空数组。

  1. 如何从构造函数中获取props 值?

    非常感谢您的帮助。

    import React, { Component } from 'react';
    import { View, Text, StyleSheet } from 'react-native';
    import { TabViewAnimated, TabBar, SceneMap } from 'react-native-tab-view';
    
    export default class TabBarMenu extends Component {
    
      constructor(props) {
        super(props);
        console.log(this.props) // showing empty array
    
        this.state = {
          index: 0,
          routes: [
            { key: '1', title: 'Weather' },
            { key: '2', title: 'News' },
            { key: '3', title: 'Photos' },
          ],
        };
      }
    
      _FirstRoute = this.props => (
        <View style={styles.container}>
          <Text style={styles.textStyle}>1</Text>
          <Text style={styles.textStyle}>{this.props.description}</Text>
          <Text style={styles.textStyle}>{this.props.time}</Text>
          <Text style={styles.textStyle}>{this.props.temp}</Text>
        </View>
      )...
    

【问题讨论】:

  • TabBarMenu 是否呈现?您需要渲染 _getFiveWeather 函数,但这可能是更糟糕的设计,因为您试图在 _getFiveWeather 函数中做太多事情。将获取方法和渲染方法分开,以便您可以设置 json 的状态。请注意:您不能在渲染方法中设置状态,否则这将导致 INFINITE 重新渲染。

标签: json reactjs react-native


【解决方案1】:

您的_getFiveWeather 定义本质上是无用的,因为在获取数据之后,您实际上并没有对映射的组件做任何事情。您只需执行地图操作,然后就是这样 - 没有其他任何事情发生。

获取数据的方法应该只关心——获取数据;它应该与生成组件无关。您应该在获取新数据后使用新数据设置状态。成功获取信息后类似于this.setState({ ... })

然后,在render() 方法中,验证是否有要渲染的内容。也就是说,如果你的组件状态属性中有任何天气信息,你可以做一些映射来动态创建你需要渲染的组件。

我在你的代码中没有看到 render() 方法,所以我认为你应该专注于学习基础知识。从渲染()开始。不要试图一次做太多事情。

【讨论】:

    猜你喜欢
    • 2019-03-24
    • 2019-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2018-05-23
    • 1970-01-01
    相关资源
    最近更新 更多