Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Axios get请求位于无限循环中_Reactjs_Axios - Fatal编程技术网

Reactjs Axios get请求位于无限循环中

Reactjs Axios get请求位于无限循环中,reactjs,axios,Reactjs,Axios,我有这个Reactjs应用程序,它正在使用惊奇漫画API。但是一旦它运行,它就开始发出GET请求,并且不再停止 我已经尝试对我的axiosget方法使用异步/等待和基于承诺的配置,但结果是一样的:ifinite请求 Main.js export default class Main extends Component { constructor(props) { super(props); this.state = { heroes: [], sear

我有这个Reactjs应用程序,它正在使用惊奇漫画API。但是一旦它运行,它就开始发出GET请求,并且不再停止

我已经尝试对我的axiosget方法使用异步/等待和基于承诺的配置,但结果是一样的:ifinite请求

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模式)。但即使如此,问题还是出现了。

这是因为您的if条件,
prevState.searc
始终是未定义的,因为它不存在,因此不等于
this.state.search
componentDidUpdate
检查条件(通过),运行逻辑,逻辑更新状态,检索
componentDidUpdate
,循环是无止境的:

  componentDidUpdate(prevProps, prevState) {
    if (prevState.searc !== this.state.search) {
      this.loadHeroes();
    }
  }
你可能是说:

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