繁体   English   中英

如何在 React 中的单击按钮上使用 fetch API 设置状态

[英]how to setState with fetch API on click button in React

我是 React 的新手,想要获取 API。这个想法是:当我点击一个按钮时,它应该首先改变一个状态,然后获取数据。 现在不像我预期的那样工作......当我点击按钮时,它显示来自 4 个城市的数据(因为 init 状态),然后我点击特定城市(例如坦佩雷)但是点击之后什么都没有发生,当我点击另一个按钮时(例如赫尔辛基)它显示我以前点击的按钮(坦佩雷市)的数据....如何修复它? 我使用 console.log 来显示数据,因为它只是测试。 如果您能看看我的组件,我将不胜感激。 谢谢!

App.jsDropBar.js

------------------
//main component in App.js file

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cityId: '658225,655195,650225,634964&units=metric',
      multi: 'group'
    }
  }

  getWeather = ({ currentTarget }) => {
fetch(`http://api.openweathermap.org/data/2.5/${this.state.multi}?id=${this.state.cityId}&appid=${API_KEY}`)
      .then(response => response.json())
      .then(data => {

        this.setState({
          cityId: currentTarget.id,
          multi: currentTarget.value
        })
        console.log(data);
      });
  };

  render() {
    return (
      <MainLayout>
        <div className="App">Hello!</div>
        <DropBar getWeather={this.getWeather} />
      </MainLayout>
    );
  }
}

export default App;

------------------
//Buttons component in DropBar.js file

 const DropBar = (props) => {

  return (
    <form >
      <Button id="634964" value="weather" onClick={props.getWeather}>Click Tampere!</Button>
      <Button id="658225" value="weather" onClick={props.getWeather}>Click Helsinki!</Button>
      <Button id="655195" value="weather" onClick={props.getWeather}>Click Jyvaskila!</Button>
      <Button id="650225" value="weather" onClick={props.getWeather}>Click Kuopio!</Button>
      <Button
        id="658225,655195,650225,634964&units=metric"
        value="group"
        onClick={props.getWeather}
      >
        All kaupungit!
      </Button>
    </form>
  );

}

export default DropBar;```


请使用 setState 回调

getWeather = ({ currentTarget }) => {
  this.setState({
    cityId: currentTarget.id,
    multi: currentTarget.value
  }, () => {
    fetch(`http://api.openweathermap.org/data/2.5/${this.state.multi}?id=${this.state.cityId}&appid=${API_KEY}`)
      .then(response => response.json())
      .then(data => {
        console.log(data);
      });
  })
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM