2016-06-13 8 views
4

私はReactとRedux、WebSocketを使用していくつかのサーバーサイドイベントを処理しています。コンポーネント(外部モジュール、つまりWebSocket)外部のストア関数(ディスパッチ、getState)を使用します。

機能を割り当てるコンポーネントから、mapDispatchToProps()機能経由でディスパッチャにアクションをディスパッチできます。

しかし、コンポーネントの外でアクションを実行するとどうなりますか?たとえば、受信したwebSocketのイベントで発生します。別のスクリプトからstore.dispatchを呼び出す

は、ストアが適切にインポートされている場合でも

がそうするどのような方法があります(発送は定義されていない)、参照エラーを返すのだろうか?ここで

は私のアプリストアの設定機能である:カスタムミドルウェアを使用する方法について

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

答えて

3

方法:

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 

ここでインスタンス化ストアアプリのエントリポイントはありますか?

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

でカスタムミドルウェアを追加