用react钩子设置全局函数/变量

时间:2019-09-30 09:19:11

标签: reactjs global react-hooks

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

出现错误

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

  });

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

2 个答案:

答案 0 :(得分:2)

问题出在导入语句中。

将导入语句更改为:

import {getData} from  "../function"

答案 1 :(得分:2)

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

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

使用示例

  api.getData(URL,setCount);