2017-02-15 24 views
0

希望這不算作「意見」問題。我正在關注this教程,此人在他們的src/index.js文件中調用store.dispatch(loadCats()) - 入口點。我有以下文件結構(與教程中的基本相同)。在Redux中應該在哪裏存儲調度以進行異步操作?

. 
├── README.md 
├── package.json 
├── public 
│   ├── favicon.ico 
│   └── index.html 
└── src 
    ├── actions 
    │   ├── actionTypes.js 
    │   └── partActions.js 
    ├── api 
    │   └── partApi.js 
    ├── components 
    │   ├── App 
    │   │   ├── index.css 
    │   │   ├── index.js 
    │   │   └── index.test.js 
    │   ├── Header 
    │   │   └── index.js 
    │   └── ThingCard 
    │    ├── index.css 
    │    └── index.js 
    ├── containers 
    │   └── ThingsGrid 
    │    ├── index.css 
    │    └── index.js 
    ├── index.css 
    ├── index.js 
    ├── pages 
    │   ├── DragonsPage 
    │   │   └── index.js 
    │   ├── ThingsPage 
    │   │   └── index.js 
    │   └── KittensPage 
    │    └── index.js 
    ├── reducers 
    │   ├── initialState.js 
    │   ├── partsReducer.js 
    │   └── rootReducer.js 
    ├── routes.js 
    └── store 
     └── configureStore.js 

我有這些pages這是容器的容器。換句話說,一個頁面可以有多個與某個邏輯類別相關的容器,如Thing,KittenDragon。對我來說,從每個page調用像store.dispatch(loadThings())這樣的函數是有道理的。這是一種常見的模式還是我想念一些東西?

// src/index.js 
    const store = configureStore() 
    store.dispatch(loadParts()) 

    ReactDOM.render(
     <Provider store={store}> 
      <Router history={browserHistory} routes={routes}/> 
     </Provider>, 
     document.getElementById('root') 
    ); 

這就是我如何通過使用react-redux將商店傳遞到路線。如果可以在我的page組件中發送操作,我將如何訪問此商店?

回答

2

因此,首先,要從組件頁面訪問您的商店,可以使用mapStateToProps redux方法。通常情況下,您將調度功能留在減速器內部,或者僅在調用減速器開關之前創建action folder才能執行操作。我沒有得到你想要訪問這個商店文件夾的原因。

import { connect } from 'react-redux' 

class ExampleComponent extends Component { 

    componentWillMount() { 
    this.props.exampleAsyncFunction() 
    } 

    render() { 
    return <p> 'anything' </p> 
    } 

} 

const mapStateToProps = (state) => { 
    return ({ 
    admin: state.admin, 
    }) 
} 

const mapDispatchToProps = (dispatch) => ({ 
    exampleAsyncFunction: reqObj => { 
    dispatch(adminActions.exampleAsyncFunction()) 
    } 
} 

export default connect(
    mapStateToProps, 
    mapDispatchToProps 
)(ExampleComponent) 
+0

我對「操作文件夾」和「商店文件夾」這兩個術語感到困惑。另外,它在減速器內派發動作有什麼好處呢?我的推理是,不是在應用程序加載時從服務器加載每個資源,而是在SomePage調度獲取操作時,reducer將其消耗 - >頁面在其props中獲取資源 - > page將資源傳遞給容器 –

+0

另外, t知道'mapDispatchToProps'是如何使用的 - 這樣工作正常,謝謝!想對上面提到的事情做一些澄清^ –