如何设置多个对象的状态并传递给其他组件?

时间:2018-11-05 20:09:57

标签: reactjs react-native

我是本机新手。我尝试了很多方法来从openweathermap的API获取JSON数据数组,但是没有用。我想要一些建议和指南。 我只是获取JSON数据,并希望从JSON数据中设置多个对象的状态。

JSON数据示例。我想从list []中的2个数组中获取温度,湿度,描述和图标。

"list":[  
  {  
     "dt":1541440800,
     "main":{  
        "temp":25.85,
        "temp_min":25.85,
        "temp_max":27.35,
        "pressure":1022.17,
        "sea_level":1023.04,
        "grnd_level":1022.17,
        "humidity":100,
        "temp_kf":-1.5
     },
     "weather":[  
        {  
           "id":500,
           "main":"Rain",
           "description":"light rain",
           "icon":"10n"
        }
     ],
     "dt_txt":"2018-11-05 18:00:00"
  },
  {  
     "dt":1541451600,
     "main":{  
        "temp":26.38,
        "temp_min":26.38,
        "temp_max":27.5,
        "pressure":1021.34,
        "sea_level":1022.24,
        "grnd_level":1021.34,
        "humidity":100,
        "temp_kf":-1.12
     },
     "weather":[  
        {  
           "id":802,
           "main":"Clouds",
           "description":"scattered clouds",
           "icon":"03n"
        }
     ],
     "dt_txt":"2018-11-05 21:00:00"
  }

这是我的JSON提取组件。我想通过将状态传递给前端组件来显示与数组不同的数据。

export default class Forecast extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hourlyForecast: {}
    };
  }

  fetchData = () => {
    fetch(
      `http://api.openweathermap.org/data/2.5/forecast?q=${
        this.props.currentCity
      }&units=metric&appid=${API_KEY}`
    )
      .then(response => response.json())
      .then(json => {
        this.setState({
          hourlyForecast: {
            temp: json.list[0].main.temp,
            humidity: json.list[0].main.humidity,
            icon: json.list[0].weather[0].icon,
            description: json.list[0].weather[0].description,
            date_time: json.list[0].dt_txt
          }
        });
      })
      .catch(error => {
        console.warn(error);
      });
  };

  componentDidMount = () => this.fetchData();

  render() {
    return (
      <Container>
        <Content>
        <ForecastCards {...this.state.hourlyForecast} />
        <ForecastCards {...this.state.hourlyForecast} />
        </Content>
      </Container>
    );
  }
}

这是我的前端组件。

export default class ForecastCards extends Component {
  render() {
    return (
          <Card>
            <CardItem>
              <Body>
                <View style={{flex: 1, flexDirection: "row"}}>
                  <View>
                    <Text>{this.props.date_time}</Text>
                    <Text>Temperature: {this.props.temp} °C</Text>
                    <Text>Humidity: {this.props.humidity} %</Text>
                  </View>
                  <View style={{marginLeft: 100}}>
                     <Image
                      style={{ width: 60, height: 60 }}
                      source={{
                        uri: `http://openweathermap.org/img/w/${
                          this.props.icon
                        }.png`
                      }}
                    />
                    <Text>{this.props.description}</Text>
                  </View>
                </View>
              </Body>
            </CardItem>
          </Card>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您在这里找到解决方法

fetchData = () => {
  fetch(
    `http://api.openweathermap.org/data/2.5/forecast?q=${this.props.currentCity}&units=metric&appid=${API_KEY}`
  )
  .then(response => response.json())
  .then(json => {
    this.setState({
      hourlyForecast: {
        temp: json.list[0].main.temp,
        humidity: json.list[0].main.humidity,
        icon: json.list[0].weather[0].icon,
        description: json.list[0].weather[0].description,
        date_time: json.list[0].dt_txt
      }
    });
  })
  .catch(error => {
    console.warn(error);
  });
};

componentDidMount = () => this.fetchData();

render() {
  return (
    <Container>
      <Content>
        <ForecastCards hourlyForecast={this.state.hourlyForecast} />
        <ForecastCards hourlyForecast={this.state.hourlyForecast} />
      </Content>
    </Container>
  );
}

这是我的前端组件。

export default class ForecastCards extends Component {
  render() {
    return (
      <Card>
        <CardItem>
          <Body>
            <View style={{flex: 1, flexDirection: "row"}}>
              <View>
                <Text>{this.props.hourlyForecast.date_time}</Text>
                <Text>Temperature: {this.props.hourlyForecast.temp} °C</Text>
                <Text>Humidity: {this.props.hourlyForecast.humidity} %</Text>
              </View>
              <View style={{marginLeft: 100}}>
                 <Image
                  style={{ width: 60, height: 60 }}
                  source={{
                    uri: `http://openweathermap.org/img/w/${
                      this.props.hourlyForecast.icon
                    }.png`
                  }}
                />
                <Text>{this.props.hourlyForecast.description}</Text>
              </View>
            </View>
          </Body>
        </CardItem>
      </Card>
    );
  }
}

ForecastCards.propTypes = {
  hourlyForecast: PropTypes.object
}

设置状态很好。用于传递道具<ForecastCards hourlyForecast={this.state.hourlyForecast} />

使用ForecastCardsForecastCards.propTypes = { hourlyForecast: PropTypes.object }组件中提供PropType

要访问date_time或其他任何键,请使用this.props.hourlyForecast.date_timethis.props.hourlyForecast.{key}

希望这会对您有所帮助。