在React中更新对象数组的几个属性(onClick = {将cels更改为在setState上的fahrenheit})

问题描述 投票:0回答:1

更新:我已经修改了我的问题并更改了我的示例代码,以使其尽可能简单和自我解释。

从openweathermap API我得到一个对象数组......与此非常类似:

    // Returned JSON already parsed ( I used "Axios" for the GET request)
    const obj = [
      {name: "Hong-Kong", main: {temp: 34, humidity: 33}}, 
      {{name: "Ontario", main: {temp: 14, humidity: 3}}, 
      {{name: "Poland", main: {temp: 54, humidity: 9}}
    ]

我的应用程序组件看起来像这样:

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      data: obj
    }
  }
  render() {
    return (
       <div>
         <Card weatherData={this.state.data}/>
       </div>

    )
  }
}

在我的卡组件中,我使用.map来渲染3张漂亮的卡片,其中包含我从App组件的状态作为道具(weatherData)传递到我的卡组件的所有天气信息:

function Class(props) {
  const convertToFahrenheit = e => {
    e.preventDefault();
    // Grab every single celsius and do the math to fahrenheit
    // I would need some sort of dynamic variable on the {d.main.temp}
  }


    {props.weatherData.map(d => {
       return (
         <div>
           <p>{d.name}</p>
           <p>{d.main.temp}</p>
           <p>{d.main.humidity}</p>
           <button onClick={convertToFahrenheit}>to_fahrenheit</button>
           <button>to_celsius</button>
         </div>
       )
    })}
}

基本上,当我点击华氏温度按钮时,我希望能够将卡片组件上的摄氏温度更改为华氏温度,反之亦然。

我不知道是否应该在App Component上管理它并尝试更新状态温度或在类功能组件中找到一种巧妙的方法。我搞不清楚了。

请建议,帮助,我已经坚持了一个星期......我应该使用Inmutable和Redux这种情况吗?

javascript reactjs
1个回答
0
投票

第一个无状态组件没有方法,你的Card组件应该是有状态的。

class Card extends React.Component{

  convertToFahrenheit = e => {
    // Grab every single celsius and do the math to fahrenheit
    // I would need some sort of dynamic variable on the {d.main.temp}
  }

render() {
  const { weatherData } = this.props;
  return (
    <div>
    weatherData.map(d => {
      return (
        <div>
          <p>{d.name}</p>
          <p>{d.main.temp}</p>
          <p>{d.main.humidity}</p>
          <button onClick={this.convertToFahrenheit}>to_fahrenheit</button>
          <button>to_celsius</button>
        </div>
      )
    })
    </div>
  )
}
}
© www.soinside.com 2019 - 2024. All rights reserved.