2015-11-11 17 views

答えて

7

私はちょうどそれらを返す関数で、私のルートを包みました。

これは、彼らがそのstore引数へのアクセス権を持っているとdispatch()ものをすることができますので、任意のonEnter/onExit機能もそこに定義されていますが、引数

としてReduxのストアを渡すことができます。

import React from 'react' 
import { IndexRoute, Route } from 'react-router' 

import App from './components/app' 
import FourOhFour from './components/pages/404' 
import Home from './components/home' 
import LogIn from './components/account/log_in' 
import ResetPassword from './components/account/reset_password' 
import SignUp from './components/account/sign_up' 

export function getRoutes (store) { 
    function doSomething (thing) { 
    store.dispatch(addToDoActionCreator(thing)) 
    } 

    function authenticate (nextState, replaceState) { 
    const { currentUser } = store.getState(); 

    if (!currentUser) { 
     replaceState(null, '/log-in'); 
    } 
    } 

    return (
    <Route path='/' component={App}> 
     <IndexRoute component={Home} onEnter={(nextState, replaceState)=>{doSomething('get coffee')}} /> 

     <Route path='log-in' component={LogIn} onEnter={authenticate} /> 
     <Route path='sign-up' component={SignUp} /> 
     <Route path='reset-password' component={ResetPassword} /> 

     <Route path="*" component={FourOhFour}/> 
    </Route> 
); 
} 

サーバー側(私にとってはexpress.js)では、ミドルウェアで比較的早くreduxストアを確立します。このようなもの。

server.use((req, res, next) => { 
    const createStoreWithMiddleware = applyMiddleware(
    thunkMiddleware 
)(createStore); 
    res.store = createStoreWithMiddleware(rootReducer); 

    next(); 
} 

これでストアはレスポンスオブジェクトにアタッチされ、他のミドルウェア/ルートでも使用できます。彼らは状態(res.store.getState())を取得し、更新状態にディスパッチすることができます。

3

あなたのレフィックスストアを別々のファイルに作成し、必要なときにそれを必要とするだけです。

// store.js 
 

 
import { createStore } from 'redux' 
 
import todoApp from './reducers' 
 
    
 
export default createStore(todoApp);

// the file where you define your routes and onEnter 
 

 
import { render } from 'react-dom'; 
 
import { Router, Route } from 'react-router'; 
 
import store, { dispatch } from './store.js'; 
 

 
function enterHandler(){ 
 
    dispatch(allTheGoodStuff); 
 
} 
 

 
render(
 
    <Router> 
 
    <Route onEnter={ enterHandler } ... 
 
)

+1

しかし、普遍的なアプリケーションではうまくいかないでしょう。 –

+1

私はこの戦略を試して競合状態に遭遇したので、ymmvを見てください:https://github.com/rackt/react-redux/issues/181#issuecomment-164626032 –

+1

状況についてのいくつかの詳細を教えてください.DanAbramov? –

関連する問題