无法让 componentDidUpdate() 停止循环

Sil*_*ERE 6 javascript reactjs axios

我正在尝试使用 Axios 从公共 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;
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。

Shu*_*tri 3

假设您需要在每次状态更改时采取操作,则需要在触发之前检查状态是否已更新,action否则componentDidUpdate每当组件更新时都会进行 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);
          })
    }
}
Run Code Online (Sandbox Code Playgroud)