我在JS中的React Native中使用MobX学习Axios。我正在尝试使用该技术从API获取数据并传输到视图,但我只传递空数组或未定义的
首先,当我通过Axios调用API时,我有一个文件
我认为在这个地方是错误的,但我不知道在哪里
import API from "./api";
export function exampleGroupsAPI() {
return API.get('/example-groups').then(response => response.data)
}
我为数据存储的下一个文件
import {makeAutoObservable, runInAction} from 'mobx';
import {exampleGroupsAPI} from '../api/agent';
export default class ExampleGroupsStore {
exampleGroups = [];
loadingInitial = false;
constructor() {
makeAutoObservable(this);
}
setLoadingInitial = state => {
runInAction(() => {
this.loadingInitial = state;
});
};
loadExampleGroups = async () => {
const result = await exampleGroupsAPI();
runInAction(() => {
this.exampleGroups = result.data;
})
};
}
该组件是我尝试显示数据的地方,但这个console.log只显示未定义或空的数组
import React, {useEffect} from 'react';
import {Text, StyleSheet} from 'react-native';
import {observer} from 'mobx-react-lite';
import {useExampleGroupsStore} from '../../app/stores/hooks';
const ExampleGroupsList = () => {
const { exampleGroups, loadExampleGroups} = useExampleGroupsStore();
useEffect(() => {
loadExampleGroups();
}, [loadExampleGroups]);
console.log(exampleGroups)
return (
<Text>
TEST
</Text>
);
};
export default observer(ExampleGroupsList);
最后一个是导出存储时的文件
import {StoreContext} from './storeProvider';
export function useExampleGroupsStore() {
const store = useContext(StoreContext);
return store.ExampleGroupsStore;
}```