反应js钩useEffect无限循环

时间:2019-03-24 21:19:49

标签: javascript reactjs react-hooks

我正在玩React钩子,并跟踪https://www.valentinog.com/blog/hooks/上的tutorail。我将空数组作为文档之后的第二个参数,并且由于某些原因我仍然遇到无限循环。

import React, { useState, useEffect } from "react";
export default function useDataLoader() {
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch("http://api.icndb.com/jokes/random")
      .then(response => response.json())
      .then(data => {
        setData(data.value.joke)
        console.log(data)
      }, []);
  });
  return (
    <div>
      <div>
        {data}
      </div>
    </div>
  );
}


import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Hook from './components/Hook'
import DataLoader from './components/DataLoader'

class App extends Component {
  render() {
    return (
      <div className="App">
        <Hook />
        <DataLoader/>
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:2)

[]放在错误的位置。您将其传递给fetch().then()而不是useEffect

  useEffect(() => {
    fetch("http://api.icndb.com/jokes/random")
      .then(response => response.json())
      .then(data => {
        setData(data.value.joke)
        console.log(data)
      });
  }, []);