【问题标题】:How to use math operation with 2 props?如何使用 2 个道具进行数学运算?
【发布时间】:2018-12-08 02:31:29
【问题描述】:

示例:我想乘以从 API 获取的 2 个道具( Temp* 湿度)并希望在新值出现时更新结果(用户输入新城市然后温度和湿度改变)

这是我的 fetching.js

fetchData = q => {
fetch(
  `http://api.openweathermap.org/data/2.5/weather?q=${q},th&units=metric&APPID=${API_KEY}`
)
  .then(response => response.json())
  .then(json => {
    this.setState({
      currentWeather: {
        temp: json.main.temp,
        icon: json.weather[0].icon,
        description: json.weather[0].description,
        humidity: json.main.humidity,
        datetime: json.dt
      }
    });
  })
  .catch(error => {
    console.warn(error);
  });
};

这是我的前端

  render() {
    return (
      <View style={styles.viewStyle}>
        <View style={styles.dataStyle}>
          <Text style={styles.textStyle}>Temperature </Text>
          <Text style={styles.textStyle}>{this.props.temp} °C</Text>
        </View>
        <View style={styles.dataStyle}>

      <Image
            style={{ width: 100, height: 100 }}
            source={{
          uri: `http://openweathermap.org/img/w/${this.props.icon}.png`
        }}
      />
      <Text style={styles.textStyle}>{this.props.description}</Text>
    </View>
    <View style={styles.dataStyle}>
      <Text style={styles.textStyle}>Humidity</Text>
      <Text style={styles.textStyle}>{this.props.humidity} %</Text>
    </View>
  </View>
);
}

我想计算当温度和湿度传递到组件时的热指数并显示在湿度部分。

【问题讨论】:

  • 你在尝试实现这一点时遇到了什么困难?
  • 只需设置一个名为heatIndex 的新currentWeather 属性并将其设置为json.main.temp * json.mainhumidy。为什么那行不通?
  • 抱歉,我是 javascript 新手。我只了解 state 和 props 的基本知识,但我不知道它能做什么。

标签: javascript reactjs react-native


【解决方案1】:

您应该在 componentDidMount() 生命周期事件中调用您的 fetch。如果 state 中的任何数据发生变化,那么组件将被重新渲染。

componentDidMount 仅在客户端第一次渲染后执行。这是 AJAX 请求和 DOM 或状态更新应该发生的地方。此方法还用于与其他 JavaScript 框架和任何延迟执行的函数(如 setTimeout 或 setInterval)集成。我们正在使用它来更新状态,以便我们可以触发其他生命周期方法。

http://www.tutorialspoint.com/reactjs/reactjs_component_life_cycle.htm

【讨论】:

  • 谢谢。我需要越来越多地练习生命周期。
  • @artaro 如果您认为这是解决问题的好方法,请毫不犹豫地投票并勾选它已解决
【解决方案2】:

如果你想在props 传入组件时乘以props,则使用componentWillReceiveProps 方法。

每当组件收到新的 props 时,都会执行 componentWillReceiveProps 方法。

componentWillReceiveProps(Props) {
          let heat_index = props.Temp* props.Humidity;
          this.setState({heat_index : heat_index});
        }

    render() {
        return (
       <View>
      <Text> The Heat Index is {this.state.heat_index} </Text>
      </View>
    );
}

【讨论】:

  • @artaro 如果您认为这是解决问题的好方法,请毫不犹豫地投票并勾选它已解决
猜你喜欢
  • 1970-01-01
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
相关资源
最近更新 更多