【发布时间】:2017-10-18 16:20:32
【问题描述】:
我正在自学 React。我有一些问题。我正在尝试将数据提取到另一个组件。在映射 JSON 数据后,我尝试setState。但它显示错误“setState is not a function”。
-
映射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), 时,它显示的是空数组。
-
如何从构造函数中获取
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