使用react hooks设置全局函数/变量

问题描述 投票:0回答:2

我正在尝试获取多个要在仪表板中显示的信息集市,因此我编写了一个函数以使事情更加模块化,并创建了一个全局函数,但我有一个错误使执行停止。

这里是错误

TypeError: _function__WEBPACK_IMPORTED_MODULE_11__ is not a function

这里是我的函数的声明,位于一个名为function.js的文件中

export const getData=(url,callBack) =>{

    fetch(url)
    .then(response => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error("Something went wrong");
      }
    })
    .then(jsonResponse => {
      callBack(jsonResponse);
      return jsonResponse;
    })
    .catch(error => {
      console.log(error);
    });

  }

这里导入和使用

import * as getData from  "../function"



const App = () => {
  const URL="http://...";

  const [count, setCount]=useState(0);
  const [data, setData] = useState([]);



  useEffect(() => {
   getData(URL,setCount);

  });

我想在每个屏幕上调用此功能

reactjs global react-hooks
2个回答
0
投票

问题出在导入语句中。

将导入语句更改为:

import {getData} from  "../function"

0
投票

验证相对路径导入并更改为

  import *  as api from  "../function". 

使用示例

  api.getData(URL,setCount);
© www.soinside.com 2019 - 2024. All rights reserved.