我正在使用 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/