如何将redux发送到外部提供商



当应用程序处于退出状态时,我正试图将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>
);
}

您可以首先像一样导出您的商店

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在下面的评论中所说,在真正必要之前,不建议这样做。

因此,我将提到一个实际的用例。比方说,一旦API调用完成,您想在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);
});
});
};

最新更新