【问题标题】:how to make api calls in reactjs new hook api and share that across components?如何在 reactjs new hook api 中进行 api 调用并跨组件共享?
【发布时间】:2019-03-31 23:17:42
【问题描述】:

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

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)
}

【问题讨论】:

  • 是的,当然,感谢您的快速回复。

标签: javascript reactjs react-hooks


【解决方案1】:

您可以创建一个自定义挂钩,该挂钩会在您的网络请求完成时创建一个新的状态 advice

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

示例

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>

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 2018-03-10
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多