我正在使用OpenWeatherMap API在React中创建一个天气应用程序。有输入表单和一个按钮,当我单击该按钮时,我希望看到城市名称。我这样做是从API接收数据的,但是我可以在控制台中登录时却无法在屏幕上呈现数据。
为此,我使用了三个分开的文件。App.js,Form.js(用于提交条款)和weather.js(用于API配置)。
我猜测我需要映射接收到的数据,但尚未成功。
class App extends React.Component {
state = {
city: null,
}
getWeather = async city => {
const response = await weather.get('/forecast', {
params: {
q: city
}
});
this.setState({
city: response.name,
})
console.log(city); <--- This works
}
render() {
return (
<div>
<Form loadWeather={this.getWeather} />
<p>{this.state.city}</p> <--- This doesn't work
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
class Form extends React.Component {
state = { term: '' };
onFormSubmit = (event) => {
event.preventDefault();
this.props.loadWeather(this.state.term);
this.refs.textInput.value = '';
}
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input
ref="textInput"
type="text"
value={this.state.term}
onChange={event => this.setState({term: event.target.value})}
/>
<button>Get Weather</button>
</form>
</div>
);
}
}
export default Form;
Run Code Online (Sandbox Code Playgroud)
我将把{this.state.name}作为道具传递给子组件,但到目前为止,如果自己接收的数据甚至不会出现在该组件上。
“ this.setState”是一个函数,应这样调用。
this.setState({
city: response.name,
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
55 次 |
最近记录: |