【问题标题】:How do i dispatch redux outside provider?我如何在供应商之外派遣 redux?
【发布时间】:2021-03-24 15:14:16
【问题描述】:

我正在尝试在应用程序退出时将通知从 firebase 保存到 redux。

但我需要在 app.js 中执行此操作,我什至不在组件上时如何调度 redux 操作?

这就是我想要做的事情

componentDidMount(){
  messaging().getInitialNotification().then(remoteMessage) => { 
    dispatch(action({
      notification:true,
      data:remoteMessage.data
    }));
  }
}
  
render(){
  return(
    <Provider context={MyContext} store={store}>
      <App />
    </Provider>
  );
}

【问题讨论】:

  • store.dispatch(whatever).

标签: javascript react-native redux


【解决方案1】:

你可以先导出你的店铺喜欢

export const store = createStore(
  combineReducers({
    auth: authReducer,
    team: teamReducer,
  }),
  applyMiddleware(thunk),
);

<Provider context={MyContext} store={store}>
  <App />
</Provider>

确保这是您传递给提供者的同一家商店

然后你可以在任何你想要的地方导入这个商店并使用它

import {store} from './index';
import * as actions from './actions';

store.dispatch(actions.getMySolution());

学习愉快!

编辑: 正如@markerikson 在下面的 cmets 中所说,除非确实有必要,否则不建议这样做。

所以,我将提到一个实际用例。 假设您想在 API 调用完成后调度一个操作来设置加载器和取消设置加载器。

import {store} from './index';
import * as actions from './actions';
import axios from 'axios';

export const get = (params) => {
  return new Promise((resolve, reject) => {
    store.dispatch(actions.setLoading());
    axios
      .get(url)
      .then((data) => {
        store.dispatch(actions.stopLoading());
        resolve(data.data);
      })
      .catch((e) => {
        store.dispatch(actions.stopLoading());
        reject(e);
      });
  });
};

【讨论】:

  • 谢谢先生:D
  • 请注意,我们特别建议反对尝试将商店导入代码库中的其他文件,除非绝对有必要:redux.js.org/style-guide/…。在这个特定示例中,&lt;App&gt; 已经在 &lt;Provider&gt; 中,因此您应该能够将类组件包装在 connect() 中,并通过 mapDispatch 参数从组件内正常调度操作。
  • 谢谢,@markerikson 我也应该提到这一点。我现在添加它。
猜你喜欢
  • 2020-11-20
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 2023-02-24
  • 1970-01-01
  • 2021-07-09
  • 2020-06-07
  • 2014-04-26
相关资源
最近更新 更多