如何在Axios请求工具函数中使用MobX Store的值?
在Axios工具函数中使用MobX Store的几种实现方式
下面提供三种实用方案,你可以根据项目场景选择:
方案一:将Store实例作为参数传入工具函数
这是最直观、低耦合的方式,调用工具函数时直接传入当前Store实例,适合组件或其他场景调用API时使用。
修改工具函数
// Utility function in different file export function makeApiCall(sampleStore) { // 直接使用传入的Store实例中的值 const userId = sampleStore.user.userId; // 发起Axios请求 return axios.get(`/api/user/${userId}`); }
调用示例(以React组件为例)
import SampleStore from './SampleStore'; import { makeApiCall } from './api-utils'; // 创建Store实例 const store = new SampleStore(); // 调用API工具函数 makeApiCall(store).then(response => { // 处理请求响应 });
方案二:创建Store全局单例
如果项目全局只需要一个Store实例,可以提前创建单例,工具函数直接导入使用即可。
创建单例Store文件(如store/index.js)
import SampleStore from './SampleStore'; // 全局唯一的Store实例 export const sampleStore = new SampleStore();
修改工具函数
// Utility function in different file import { sampleStore } from './store'; export function makeApiCall() { // 直接使用全局单例中的值 const userId = sampleStore.user.userId; return axios.get(`/api/user/${userId}`); }
使用示例
import { makeApiCall } from './api-utils'; // 无需传参,直接调用 makeApiCall().then(response => { // 处理请求响应 });
方案三:React项目中用MobX Provider + 自定义钩子
如果是React项目,结合MobX的Provider和自定义钩子,通过上下文获取Store实例,适合大型项目的状态管理。
配置根组件Provider
import { Provider } from 'mobx-react'; import SampleStore from './SampleStore'; const sampleStore = new SampleStore(); function App() { return ( <Provider sampleStore={sampleStore}> {/* 项目子组件 */} </Provider> ); }
创建获取Store的自定义钩子(如hooks/useStore.js)
import { useContext } from 'react'; import { MobXProviderContext } from 'mobx-react'; export function useStore() { return useContext(MobXProviderContext); }
修改工具函数并在组件中调用
// Utility function in different file export function makeApiCall(sampleStore) { const userId = sampleStore.user.userId; return axios.get(`/api/user/${userId}`); }
import { makeApiCall } from './api-utils'; import { useStore } from './hooks/useStore'; function UserComponent() { const { sampleStore } = useStore(); const fetchUser = async () => { const response = await makeApiCall(sampleStore); // 处理请求响应 }; return <button onClick={fetchUser}>获取用户信息</button>; }
内容的提问来源于stack exchange,提问作者Saket Kumar
相关产品推荐
相关产品推荐

