如何在 reactjs new hook api 中进行 api 调用并跨组件共享? [英] how to make api calls in reactjs new hook api and share that across components?

查看:27
本文介绍了如何在 reactjs new hook api 中进行 api 调用并跨组件共享?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在新的 reactjs hook api 中调用一个 restApi.并使用 useEffects 和 useState 重用数据?我只想跨组件重用数据.

import { useState, useEffect } from "react";导出默认函数 getAdvice(url) {获取(`http://api.adviceslip.com/advice`).then(res => res.json()).then(res => console.log(res)).catch(err => console.log(err)}

解决方案

您可以创建一个自定义钩子来创建您在网络请求完成时设置的新状态advice.>

从提供给 useEffect 的函数中返回一个函数,该函数在使用它的组件重新渲染或卸载组件时取消您的请求.您还可以在数组中提供您的 url 作为 useEffect 的第二个参数,以便仅在 url 实际更改时重新运行网络请求.

示例

const { useState, useEffect } = React;函数 useAdvice(url) {const [advice, setAdvice] = useState(null);使用效果(() =>{const timeout = setTimeout(() => {setAdvice(`使用 ${url} 获得一些好的建议`);}, 1000);返回 () =>清除超时(超时);},[网址]);退货建议;}功能应用(){const 建议 = useAdvice("https://google.com");返回 <div>{advice}</div>;}ReactDOM.render(, document.getElementById("root"));

<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.production.min.js"></script><script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.production.min.js"></script><div id="root"></div>

How to call a restApi in the new reactjs hook api. And reusing the data using useEffects and useState ? I want to just reuse the data across components.

import { useState, useEffect } from "react";
export default function getAdvice(url) {
    fetch(`http://api.adviceslip.com/advice`)
        .then(res => res.json())
        .then(res => console.log(res))
        .catch(err => console.log(err)
}

解决方案

You can create a custom hook that creates a new piece of state advice that you set when your network request has finished.

Return a function from the function given to useEffect that cancels your request when the component that uses it re-renders or the component is unmounted. You can also give your url in an array as the second argument to useEffect to only re-run the network request when the url actually changes.

Example

const { useState, useEffect } = React;

function useAdvice(url) {
  const [advice, setAdvice] = useState(null);

  useEffect(
    () => {
      const timeout = setTimeout(() => {
        setAdvice(`Use ${url} to get some nice advice`);
      }, 1000);
      
      return () => clearTimeout(timeout);
    },
    [url]
  );

  return advice;
}

function App() {
  const advice = useAdvice("https://google.com");

  return <div>{advice}</div>;
}

ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

这篇关于如何在 reactjs new hook api 中进行 api 调用并跨组件共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆