我有一个父组件调用App.js
:ReactJS + Redux:如何将动作创建者构建到每个组件?
...
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
@Robsonsjre我已经这样做了,但它已经到了一个过于集群的地步。太多的动作创作者,我将不得不始终浏览不相关的动作,找到我需要的动作。拥有特定组件的动作创建者可帮助我查找动作创建者,并更快地采取行动。 –