我正在尝试使用 Axios 从公共(public) API 获取数据,并显示我通过 React 应用程序获得的数据。但是当用户修改输入时,我无法在我的 componentDidUpdate() 中找到让它只渲染一次的条件。有人有想法吗?
这是我的代码:
import React, { Component } from 'react';
import axios from "axios";
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
input: "",
output: []
}
}
componentDidUpdate() {
axios.get(`https://geo.api.gouv.fr/communes?nom=${this.state.input}`)
.then(response => {
this.setState((prevState) => {
if (prevState.input !== this.state.input) {
return { output: response.data };
}
});
})
.catch(function (error) {
console.log(error);
})
}
handleInput = (event, input) => {
this.setState({input: event.target.value});
}
render() {
return (
<React.Fragment>
<label>Recherche : <input type="text" onChange={this.handleInput} /></label>
<div>
{this.state.output.map((value, index) => <p key={index}>{value.nom}</p>)}
</div>
</React.Fragment>
);
}
}
export default App;
感谢您的帮助。
最佳答案
假设您需要在每次状态更改时采取操作,您需要在触发 componentDidUpdate
中的 action
之前检查状态是否已更新,否则将进行 API 调用每当您的组件更新时。
如果您只想调用一次 API,则在 componentDidMount
中调用它
componentDidUpdate(prevProps, prevState) {
if(prevState.input !== this.state.input) {
axios.get(`https://geo.api.gouv.fr/communes?nom=${this.state.input}`)
.then(response => {
this.setState({ output: response.data });
})
.catch(function (error) {
console.log(error);
})
}
}
关于javascript - 无法让 componentDidUpdate() 停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49854097/