Where should I make AJAX and API calls in React.js function components?

前端 未结 2 1684
挽巷
挽巷 2021-01-27 11:36

I\'ve been learning more about React.js function components and have started transitioning one of my React.js applications to use them instead of the standard react components.

2条回答
  •  一向
    一向 (楼主)
    2021-01-27 12:04

    This is what React hooks gives us - ways to do side effects in functional components:

    https://reactjs.org/docs/hooks-effect.html

    from the doc page:

    If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

    for example:

    import React, { useState, useEffect } from 'react';
    
    function Example() {
      const [count, setCount] = useState(0);
    
      // Similar to componentDidMount and componentDidUpdate:
      useEffect(() => {
        //do an ajax call here
      });
    
      return (
        

    You clicked {count} times

    ); }

提交回复
热议问题