gpt4 book ai didi

javascript - ReactJS 更改 url

转载 作者:行者123 更新时间:2023-11-28 14:55:07 25 4
gpt4 key购买 nike

我正在尝试使用 React 制作天气应用程序,并且我想通过在 input 中输入城市的名称来更改城市。我有必须改变状态的函数:

 update( e ){
this.setState({cityName: e.target.value})
}

在渲染函数中我有这个:

return <div id="layout-content" className="layout-content-wrapper">
<input type="text"
onChange={this.update.bind(this)}/>
<div className="panel-list">{ persons }</div>
<h1>{this.state.coord.lon}</h1>
<h1>{this.state.cityName}</h1> //output my city name

我有一个函数,可以将 URL 中的城市名称 var 传递给 api:

UserList(city = this.state.cityName){
let apiKey = 'c24bda9c5812d6be82860b70c35d41a5';
let url = 'http://api.openweathermap.org/data/2.5/weather?q=';
let weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=c24bda9c5812d6be82860b70c35d41a5';
return $.getJSON(weatherURL).then((response) => {
this.setState({coord: response.coord});
this.setState({person: response.weather});
});
}
</div>

但它不会改变天气预报。为什么它没有改变?所有代码:

class App extends React.Component {
constructor(props){
super();
this.state = {
person: [],
coord: [],
cityName: 'London'
};
}

componentDidMount() {
this.UserList();
}

update( e ){
this.setState({cityName: e.target.value})
}

UserList(city = this.state.cityName){
let apiKey = 'c24bda9c5812d6be82860b70c35d41a5';
let url = 'http://api.openweathermap.org/data/2.5/weather?q=';
let weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=c24bda9c5812d6be82860b70c35d41a5';
return $.getJSON(weatherURL).then((response) => {
this.setState({coord: response.coord});
this.setState({person: response.weather});
});
}

render() {
const persons = this.state.person.map((item) => {
return <div>
<h1>{item['id']}</h1>
<span>{item['main']}</span>

</div>
});

return <div id="layout-content" className="layout-content-wrapper">
<input type="text"
onChange={this.update.bind(this)}/>
<div className="panel-list">{ persons }</div>
<h1>{this.state.coord.lon}</h1>
<h1>{this.state.cityName}</h1>
</div>
}
}

export default App;

最佳答案

componentDidMount在组件生命周期中只会被调用一次 - 就在组件最初安装之后。如果你想要你的update触发方法UserList ,您需要调用UserList在您的setState之后通话在 update 内完成

update( e ){
this.setState({cityName: e.target.value}, () => {
this.UserList(this.state.cityName);
});
}

您还可以通过检查 componentDidUpdate 中的先前/当前状态来完成此操作。如果您采用此方法,请注意:如果您更新了 cityName陈述 UserList 内的项目这会导致无限循环。

componentDidUpdate(prevProps, prevState) {
if (prevState.cityName !== this.state.cityName) {
this.UserList(this.state.cityName);
}
}

关于javascript - ReactJS 更改 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43214784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com