在React.js的非功能组件中使用自定义钩子

时间:2020-06-30 05:24:52

标签: javascript reactjs axios react-hooks

我试图在一个简单的非功能性组件中访问自己的自定义钩子。我想在axios中为每个请求添加Authorization标头。这就是我正在尝试的:

import axios from 'axios';
import { useStore } from '../Store/store';

const instance = axios.create({
   baseURL: 'http://apiurl.is.here/api/'
});

instance.defaults.headers.common['Authorization'] = useStore()[0].token;
export default instance;

现在,我知道自定义钩子(在这种情况下为useStore)只能在功能组件中使用。如何使用自定义钩子并在非功能组件中获取状态?

我收到此错误:

错误:无效的挂钩调用。挂钩只能在功能组件的主体内部调用。发生这种情况可能是由于以下原因之一:

  1. 您可能使用了不匹配的React和渲染器版本(例如React DOM)
  2. 您可能正在违反《钩子规则》 。是的,我是:(
  3. 您可能在同一应用中拥有多个React副本

编辑 我的商店:

import { useState, useEffect } from 'react';

let globalState = {};
let listeners = [];
let actions = {}

export const useStore = (shouldListen = true) => {

const setState = useState(globalState)[1];

const dispatch = (actionIdentifier, payload) => {
    const newState = actions[actionIdentifier](globalState, payload);
    globalState = { ...globalState, ...newState };

    for (const listener of listeners) {
        listener(globalState);
    }
}


useEffect(() => {
    if (shouldListen) {
        listeners.push(setState);
    }
    return () => {
        if (shouldListen) {
            listeners = listeners.filter(li => li !== setState);
        }
    }
}, [setState, shouldListen]);

 return [globalState, dispatch];

}


export const initStore = (userActions, initialState) => {
if (initialState) {
    globalState = {...globalState, ...initialState}
}

 actions = {...actions, ...userActions};
}

0 个答案:

没有答案
相关问题