MobX状态树商店未出现在道具中

时间:2020-08-06 02:17:13

标签: mobx mobx-state-tree mobx-react-lite

我正在使用MobX-react-lite在我的React Native应用中实现MobX状态树。我可以使用从教程中找到的钩子直接访问商店:

const useInject = <T,>(mapStore: MapStore<T>) => {
  const store = useStore();
  return mapStore(store);
};

我希望能够从道具中访问它。我感觉好像错过了一步。 我将一些数据硬编码到存储中,可以通过直接从组件访问它们来访问它们,但是我希望能够通过每个组件中的prop进行访问。 这有可能吗?

// Store.ts
import { types, Instance } from 'mobx-state-tree';

import { User } from './Models/User';

const RootStore = types.model({
  user: types.map(User),
});

export const store: RootStoreModel = RootStore.create({
  user: {
    1: {
      balance: '5046',
      email: 'email@email.com',
      firstName: 'Test',
      id: '5f02bbb4b30b4a67997fdfea',
      surname: 'Guy',
    },
  }
});

export type RootStoreModel = Instance<typeof RootStore>;
export default store;
// User.ts
import { types } from 'mobx-state-tree';

export const User = types.model({
  id: types.identifier,
  firstName: types.optional(types.string, ''),
  email: types.string,
  balance: types.optional(types.string, ''),
  surname: types.optional(types.string, ''),
})
  .actions((self: UserType) => ({
    setBalance(newBalance: string) {
      console.log('NEW BALANCE', newBalance);
      self.balance = newBalance;
    },
  }))
  .views((self) => ({
    get getBalance() {
      return self.balance;
    },
  }));

export default User;
// App.tsx
import React from 'react';
import 'mobx-react-lite/batchingForReactNative';
import { StoreProvider } from './src/Components/Context';

import store from './src/State/Store';

export default function App() {
  return (
    <StoreProvider value={store}>
      <MainNavigator initialRouteName={AppRoute.AUTH_LOADING} />
    </StoreProvider>
  );
}
// Component.tsx
import React, { useState, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { values } from 'mobx';

import { RootStoreModel } from '../State/Store';


import { useStore } from '../Components/Context';
import useInject from '../Hooks/UseInject';

const mapStore = ({ user }: RootStoreModel) => ({
  user,
});

export const MyComponent: React.FunctionComponent = (props: any) => {

  const { user } = useInject(mapStore);
  console.log('USER', user); // Returns the User from the state tree
  console.log('PROPS', props); // Doesnt contain the data from the state tree

  const UserArray = values(user);
  console.log('Array', UserArray); // Returns the array of users stored in the state tree


  return (
    <ScrollView>
      <Component />
    </ScrollView>
  );
};

export default observer(MeetingList);

0 个答案:

没有答案