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

拥有回忆 提交于 2021-02-15 07:39:37

问题


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. In my react components I had been making AJAX/API call(s) in the componentDidMount() function. Since that function doesn't exist in function components I am unsure where to put them.

I couldn't find the answer on the React.js site, the only page I could find on AJAX and APIs shows making those calls with react standard components in the componentDidMount() function.


回答1:


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 (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}



回答2:


You can use react-pure-lifecycle to add lifecycle functions to functional components.

Example:

import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';

const methods = {
    componentDidMount(props) {
    //ajax call here
    }
};

const Channels = props => (
      <h1>Hello</h1>
  )

export default lifecycle(methods)(Channels);


来源:https://stackoverflow.com/questions/58633438/where-should-i-make-ajax-and-api-calls-in-react-js-function-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!