【问题标题】:dispatch action outside component in react-sweet-state在 react-sweet-state 中调度组件外部的操作
【发布时间】:2021-08-19 10:13:55
【问题描述】:

我知道在 redux 中,我们可以在组件之外调度一个动作,只需导入 store 并使用 store.dispatch 来调度一个动作。

我正在使用 react-sweet-state,我想在组件之外调用一个操作。由于 redux-sweet-state 使用钩子,我不能这样做。

import { createStore, createSubscriber, createHook } from 'react-sweet-state';
const Store = createStore({
  initialState: {
    count: 0,
  },
actions: {
  increment: () => ({ setState, getState }) => {
    setState({
      count: getState().count + 1,
    });
  },
 },
});

const useCounter = createHook(Store);

我想在组件之外调用增量。有人可以帮助解决这个问题..谢谢

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    为此,您必须导入defaultRegistry,然后在其上使用getStore

    在您的示例中,它看起来更像这样:

    counter.store.ts

    import { createStore, createSubscriber, createHook } from 'react-sweet-state';
    const Store = createStore({
      initialState: {
        count: 0,
      },
    actions: {
      increment: () => ({ setState, getState }) => {
        setState({
          count: getState().count + 1,
        });
      },
     },
    });
    
    const useCounter = createHook(Store);
    
    export {useCounter, Store}; // export store variable here
    

    some-fn.ts

    import { defaultRegistry } from 'react-sweet-state'; // import those
    import { Store } from './counter.store.ts';
    
    const StoreInstance = defaultRegistry.getStore(Store); // we get access to store instance
    
    const someFunction = () => {
      StoreInstance.actions.increment(); 
    }
    

    【讨论】:

      【解决方案2】:

      导入你的商店然后你就可以使用它的调度功能了

      import { store } from '/path/to/createdStore';
          ​
          function testAction(text) {
            return {
              type: 'TEST_ACTION',
              text
            }
          }
          ​
          store.dispatch(testAction('StackOverflow'));
      

      【讨论】:

      • 我认为它也很简单,但似乎 react-sweet-state 实现的 store interface 与 redux 不同。不过,我只是在源头上做了一点点探查。
      猜你喜欢
      • 2019-10-23
      • 1970-01-01
      • 2016-06-06
      • 2018-11-20
      • 2017-04-03
      • 2017-11-09
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多