Axios获取请求处于无限循环中

时间:2019-10-11 19:23:15

标签: reactjs axios

我有这个Reactjs应用,正在使用 Marvel API 。但是一旦运行,它将开始发出GET请求,并且再也不会停止。

我尝试对 axios get方法使用基于异步/等待和承诺的配置,但结果是相同的:无限请求

Main.js

export default class Main extends Component {
  constructor(props) {
    super(props);
    this.state = {
      heroes: [],
      search: "",
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    this.loadHeroes();
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.searc !== this.state.search) {
      this.loadHeroes();
    }
  }

  loadHeroes = async () => {
    const PUBLIC_KEY = process.env.REACT_APP_PUBLIC;
    const PRIVATE_KEY = process.env.REACT_APP_PRIVATE;
    const timestamp = Number(new Date());
    const hash = md5.create();
    hash.update(timestamp + PRIVATE_KEY + PUBLIC_KEY);

    const response = await api
      .get(
        `/characters?limit=10&ts=${timestamp}&apikey=${PUBLIC_KEY}&hash=${hash}`
      )
      .then(response => {
        this.setState({ heroes: response.data.data.results });
      });

  handleChange(event) {
    this.setState({ search: event.target.value });
  }

  handleSubmit(event) {
    console.log("State do search: ", this.state.search);
    event.preventDefault();
  }

//render method ommited

api.js

import axios from "axios";

const api = axios.create({
  baseURL: `http://gateway.marvel.com/v1/public`
});

export default api;

请注意,在URL中,我设置了10个请求的限制(这是可用的API模式)。但是,即使发生了问题。

1 个答案:

答案 0 :(得分:1)

由于您的if条件,prevState.searc将始终是未定义的,因为它不存在,因此不等于this.state.searchcomponentDidUpdate检查条件(通过),运行逻辑,逻辑更新状态,重新触发componentDidUpdate,并且循环是无限的:

  componentDidUpdate(prevProps, prevState) {
    if (prevState.searc !== this.state.search) {
      this.loadHeroes();
    }
  }

您可能是说:

  componentDidUpdate(prevProps, prevState) {
    if (prevState.search !== this.state.search) {
      this.loadHeroes();
    }
  }