请问有人可以帮我解决这个问题吗? 我开始学习React和Redux,但是在配置redux上卡了几天。
我认为当某些东西触发了一个动作时,redux通过reducer函数的堆栈返回表示应用程序状态的对象。 不幸的是,它返回一个带有{ reducerName => reducer result }的对象,基本上意味着如果我有4个reducer,函数store.getState()会返回像这样的东西:
{
'reducerOne': entireApplicationState
'reducerTwo': entireApplicationState
'reducerThree': entireApplicationState
'reducerFour': entireApplicationState
}
我希望有人能帮助我,因为我已经用完了所有的想法 :)
这是我的application.js文件:
import React from 'react';
import ReactDom from 'react-dom';
import HomePage from 'root_views/home';
import {store} from 'root_services/redux/store';
class Application extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<HomePage/>
)
}
}
var Provider = React.createClass({
childContextTypes: {
store: React.PropTypes.object.isRequired
},
getChildContext: function () {
return {store: this.props.store}
},
render: function () {
return this.props.children;
}
});
ReactDom.render(
<Provider store={store}>
<Application/>
</Provider>,
document.getElementById('application')
);
我的store.js
import { createStore } from 'redux';
import {rootReducer} from './reducers/container';
export const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
我的container.js基本上包含了所有的reducer。
import {combineReducers} from 'redux';
// This is just the action label
import {DATA_EXCHANGE_LOAD} from 'root_services/redux/actions/container'
const initialState = {
data_exchange: {},
}
function dataExchange(state = {}, action) {
switch (action.type) {
case DATA_EXCHANGE_LOAD:
return Object.assign({}, state, {
data_exchange:{'reducerOne':'dataExchange'}
});
break;
default:
return initialState;
break;
}
};
function testReducer(state = {}, action) {
switch (action.type) {
case DATA_EXCHANGE_LOAD:
return Object.assign({}, state, {
data_exchange:{'reducerTwo':'testReducer'}
});
break;
default:
return initialState;
break;
}
};
// Export the combined reducers
export const rootReducer = combineReducers({
dataExchange,
testReducer
});
这是触发事件的操作:
export function dataExchangeLoad(){
return {
type: DATA_EXCHANGE_LOAD,
}
};
这是我的组件,触发操作的地方:
import React from 'react'
import "../components/layouts/header/header.less";
import {dataExchangeLoad} from "root_services/redux/actions/container"
export default class HomePage extends React.Component {
constructor(props, {store}) {
super(props);
store.dispatch(dataExchangeLoad());
console.log(store.getState());
}
render() {
return (
<div>
<h1>test</h1>
</div>
)
}
};
HomePage.contextTypes = {
store: React.PropTypes.object,
}
这是结果:
Object {dataExchange: Object, testReducer: Object}
combineReducers
文档页面,该页面讨论了像这样的常见问题。 - markerikson