const api_key ='09e33ec3a8beb8e071a993a59de37c17';

class WeatherApp extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      city: 'Dhaka',
      description: ''
    }
  }

  componentDidMount(){
    this.grabWeather(this.state.city);
  }

  grabWeather(city){
    fetch(`http://api.openweathermap.org/data/2.5/weather?APPID=${api_key}&q=${city}`)
    .then(response => response.json())
    .then(json => {
      this.setState({description: json.weather[0].description})
    });
    console.log("working");
  }

  render(){
    return(
      <div>
        <h1>Today's Weather</h1>
        <h2>City: { this.state.city }</h2>
        <h2>Description: {this.state.description}</h2>
      </div>
    );
  }
}

ReactDOM.render(<WeatherApp />,
document.getElementById("app"));


我已经将Babel添加为预处理器,并从快速添加中添加了React和ReactDOM。当我将其放在jsbin中而不是在Codepen中时,我可以看到输出。谁能告诉我这是怎么回事?

这是link

最佳答案

您的提取请求失败,因为您正尝试在HTTPS网站上使用HTTP从网站中提取数据。

只需更改以下网址的提取网址

http://api.openweathermap.org/data/2.5/weather?APPID=${api_key}&q=${city}



https://api.openweathermap.org/data/2.5/weather?APPID=${api_key}&q=${city}

关于javascript - ReactJS在Codepen中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50891896/

10-09 17:21