简体   繁体   中英

react js hooks useEffect infinite loop

I'm playing around with react hooks and following the tutorail at https://www.valentinog.com/blog/hooks/ . I put in the empty array as the second argument following the docs and some reason I'm still getting an infinite loop.

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;

The [] is in the wrong place. You pass it to fetch().then() instead of useEffect

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM