如何在表单提交和API获取后执行React状态更新



我有一个名为SearchLocationForm.js的React类组件,它是App.js的子级。在SearchLocationForm.js内部,我在下面有这个代码

constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
error: null,
isLoaded: false,
coordinates: [] 
}
this.appid = this.props.appid;
}
handleSubmit(location) {
fetch(
`http://api.openweathermap.org/geo/1.0/direct?q=${location}&appid=${this.props.appid}`
)
.then(res => res.json())
.then(resp => this.setState({coordinates: [resp.lat, resp.lon]}))
.catch((error) => {
console.error("there has been an issue with te GeoCode API Call", error)
})
}
render() {
return (
<LocationInput className="searchLocationForm" handleSubmit={this.handleSubmit}/>
)
}

我正试图弄清楚如何使用setState()方法用API响应更新组件状态,然后将其提升到App.js组件以便进行后续调用。

我已经查找了许多关于这个问题的答案,并尝试实现了许多解决方案,但到目前为止似乎都不起作用。你认为我的代码中发生了什么,似乎是导致了这个问题?谢谢

如果你只想更新坐标,而其他状态保持不变,你必须像这样使用排列运算符

handleSubmit(location) {

fetch(`http://api.openweathermap.org/geo/1.0/direct?q=${location}&appid=${this.props.appid}`)
.then(res => res.json())
.then(resp => this.setState({...thia.state, coordinates: [resp.lat, resp.lon]}))
.catch((error) => {
console.error("there has been an issue with te GeoCode API Call", error)
})
}

如果你想把状态提升到app.js,你必须在app.js上定义状态,并从这个组件设置状态。阅读更多关于提升状态从这里

给出完整的示例。这样做吧。

class App extends Component {
state = {
error: null,
isLoaded: false,
coordinates: [] 
}
handleSubmit(location) {

fetch(`http://api.openweathermap.org/geo/1.0/direct?q=${location}&appid=${this.props.appid}`)
.then(res => res.json())
.then(resp => this.setState({...thia.state, coordinates: [resp.lat, resp.lon]}))
.catch((error) => {
console.error("there has been an issue with te GeoCode API Call", error)
})
}

render() {
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
<SearchLocationForm state={this.state} handleSubmit={this.handleSubmit} />
</div>
);
}
}

class SearchLocationForm extends Component {
constructor(props) {
super(props);
}

render() {
return (
<LocationInput className="searchLocationForm" handleSubmit={this.props.handleSubmit}/>
)
}
}

相关内容

最新更新