使用存储函数(dispatch,getState)外部组件(外部模块即webSocket)

时间:2016-06-13 10:20:20

标签: javascript reactjs redux react-redux

我正在使用React和Redux,webSocket来处理一些服务器端事件。

我可以通过mapDispatchToProps()函数将组件中的操作分配给调度员。

但是在组件之外的触发动作呢?例如,收到webSocket的活动。

即使商店已正确导入,从其他脚本调用store.dispatch也会返回引用错误(未定义调度)

有没有办法这样做?

这是我的应用商店配置功能:

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

这里是实体商店的应用入口点:

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')
)

1 个答案:

答案 0 :(得分:3)

如何使用自定义中间件?

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)));
}

您只需在configureStore

中附加自定义中间件