I'm using React and Redux, webSocket to deal with some server side events.
I'm able to dispatch actions from component assigning a function to the dispatcher via mapDispatchToProps()
function.
But what about firing action outside the components? For instance at received webSocket's event.
Calling store.dispatch
from another script will return a reference error (dispatch is not defined) even if the store is properly imported
Is there any way to do so?
Here is my app store configuration function:
import { createStore, combineReducers, applyMiddleware, compose } from 'Redux'
import thunk from '../../node_modules/redux-thunk/src/index'
import rootReducer from '../reducers/index'
const configureStore = (initialState) => {
return createStore(
rootReducer,
initialState,
compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
)
}
export default configureStore
here is App entry point where instanciate the store:
import React, { Component } from 'React'
import { render } from 'ReactDOM'
import { Provider } from 'ReactRedux'
import { Router, hashHistory } from 'ReactRouter' //browserHistory
import actions from './actions/actions'
import configureStore from './store/configureStore'
import routes from './routes'
const store = configureStore()
console.log('store log', store)
window.storeDebug = store.getState() // FIXME: disable in production
render(
<Provider store={store}>
<Router history={hashHistory} routes={routes} />
</Provider>,
document.getElementById('container')
)
How about using a custom Middleware ?
if (!window.location) {
// App is running in simulator
window.navigator.userAgent = 'react-native';
}
// note keep the following after the window if conditions
// https://github.com/facebook/react-native/issues/4393
const socketIO = require('socket.io-client/socket.io');
const WebSocketHandler = (store) => (next) => (action) => {
const socket = socketIO(CHAT_SERVER_ADDRESS, {
transports: ['websocket']
});
socket.on('YOUR_EVENT', (data) => store.dispatch(ACTION_CREATOR(data)));
}
and you just append the custom middleware in configureStore
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.