javascript - 在组件外部(外部模块即 webSocket)使用存储函数(dispatch、getState、)

标签 javascript reactjs redux react-redux

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

我可以通过 mapDispatchToProps() 函数从组件分配一个函数到调度器来调度 Action 。

但是在组件外部触发 Action 呢?例如在接收到 webSocket 事件时。

从另一个脚本调用 store.dispatch 将返回引用错误(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')
)

最佳答案

使用自定义中间件怎么样?

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 中附加自定义中间件

关于javascript - 在组件外部(外部模块即 webSocket)使用存储函数(dispatch、getState、),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37787211/

相关文章:

javascript - js : GetElementByID() doesn't return my element

node.js - "Cannot read property ' 数据 ' of undefined"错误 whem 使用 axios 和 moxios 进行单元测试 redux 操作

javascript - 如何更改查询值(其中 : { }) with Apollo GraphQL

javascript - Preact redux 和 preact 路由器 : Routes not rendered

javascript - 为什么要求总是返回带有新内部引用的新对象

javascript - 以同步方式获取 Javascript Promise 的值

javascript - 在reactjs中使用setTimeout连续改变状态

javascript - 数组上的 redux reducer 扩展运算符不替换旧状态

javascript - 在我通过 props 的 React Enzyme 单元测试中设置状态

javascript - 在提交表单之前用 JS 动态显示行 : nothing gets printed