【发布时间】:2017-02-06 21:50:36
【问题描述】:
我有一个名为 App.js 的父组件:
...
render() {
return (
<div>
{React.cloneElement(this.props.children, this.props}
</div>
)
}
...
function mapDispatchToProps(dispatch) {
return (
actions: bindActionCreators(actions,
)
}
export default connect(
...,
mapDispatchToProps
)(App)
道具会被传递给每个组件。我想让每个组件都有它的动作创建者文件,但是我怎样才能将所有动作创建者捆绑在一起,以便动作创建者可以从App.js 级别传递下来?任何其他建议也将不胜感激,让动作创建者深入每个组件。
这是目前的结构:
ComponentOne
..actions.js //action creators
..ComponentOne.js
ComponentTwo
..actions.js //action creators
..ComponentTwo.js
App.js
actions.js//should I compile all the action creators here?
每个actions.js 都会变成这样:
let actions = {
logSayings() {
...
}
}
export default actions
在此先感谢您,并将投票/接受答案。
REDUX 设置
store.js
import { applyMiddleware, compose, createStore } from 'redux'
import rootReducer from './reducers/rootReducer'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
let finalCreateStore = compose(
applyMiddleware(thunk, logger())
)(createStore)
export default function configureStore(initialState = {articles: []}) {
return finalCreateStore(rootReducer, initialState)
}
actions.js
import { hashHistory } from 'react-router'
import { browserHistory } from 'react-router';
let actions = {
updateBar(status) {
return {
type: 'UPDATE_BAR',
indicator: status
}
}
}
export default actions
homeReducer.js
const homeReducer = function(articles = [], action){
switch(action.type){
case 'UPDATE_BAR':
return {
indicator: action.indicator,
}
default:
return articles
}
}
export default homeReducer
index.js
import React from 'react';
import {render} from 'react-dom';
import configureStore from '../../redux/store'
import { Provider } from 'react-redux'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
import App from './components/App'
import Home from './components/Home/Home'
let initialState = {
}
let store = configureStore(initialState)
render(
<div>
<Provider store={store}>
<Router history={hashHistory}>
<Route
component={App}
path='/'
>
<IndexRoute component={Home}/>
</Route>
</Router>
</Provider>
</div>,
document.querySelector('.wrapper')
)
【问题讨论】:
-
为什么要在所有子组件上都有动作创建者?为什么你不能将你的动作集中在 App 的 mapDispatchToProps 上?
-
@Robsonsjre 我已经做到了,但它已经到了过于聚集的地步。动作创建者太多,我必须总是滚动浏览不相关的,然后找到我需要的。让特定组件的动作创建者帮助我更快地查找动作创建者并采取行动。
标签: javascript reactjs redux react-jsx