将 mobx store 和 props 传递给函数

Pass mobx store and props to function

我有一个调用函数的 React 组件,我需要将注入的 mobx 存储和组件道具传递给这个函数

const Component = inject("store")(observer(({store, props}) => {
   return (
       <div>
          {_someRenderFunction(store, props)}
      </div>
   );
}));

在函数中是这样使用的

function _someRenderFunction(store, props) {
   let data = store.data;
   const { cookies } = props;
   ...
}

但是我收到错误 Cannot read property 'cookies' of undefined

如何将 store 和 component 道具传递给 _someRenderFunction

问题出在这一行:

({store, props}) => {};

您的组件仅接收道具,因此基本定义为:

(props) => {}

Inject 为您提供给定道具内的注入商店。所以你收到的是:

const props = { store: STORE_INSTANCE }

随着对象的破坏,您可以从道具中提取属性。所以这也行得通:

({ store }) => {}

在这里,您要从道具中提取 属性 商店。但在您的示例中,您还从道具中提取 属性 道具。所以在你的情况下道具应该是这样的:

const props = { store: STORE_INSTANCE, props: PROPS_OBJECT }

这不是你想要的。所以在这种情况下,对象破坏不是你想要的。以下代码应该有效:

const Component = inject("store")(observer((props) => {
   return (
       <div>
          {_someRenderFunction(props)}
      </div>
   );
}));

function _someRenderFunction(props) {
   const { cookies, store } = props;
   let data = store.data;
   ...
}