containers
import React,{Component} from 'react';
import {connect} from 'react-redux';
import actions from '../actions';
import {bindActionCreators} from 'redux';
class Counter extends Component {
render() {
let {counter, actions} = this.props;
return (
<div>
<p>次数:{counter}</p>
<button onClick={actions.increment}>加</button>
<button onClick={actions.decrement}>减</button>
<button onClick={actions.undo}>撤销</button>
<button onClick={actions.redo}>重做</button>
</div>
);
}
}
const mapStateToProps = state => ({
counter: state.counter.present
});
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(actions, dispatch)
});
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
action
export const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
export const DECREMENT_COUNTER = 'DECREMENT_COUNTER';
export const UNDO_COUNTER = 'UNDO_COUNTER';
export const REDO_COUNTER = 'REDO_COUNTER';
let actions = {
increment: () => ({
type: INCREMENT_COUNTER
}),
decrement: () => ({
type:DECREMENT_COUNTER
}),
undo:()=>({
type:UNDO_COUNTER
}),
redo:()=>({
type:REDO_COUNTER
})
};
export default actions;
reducers
import {combineReducers} from 'redux';
import undoable,{includeAction} from 'redux-undo';
import counter from './counter';
import {INCREMENT_COUNTER,DECREMENT_COUNTER,UNDO_COUNTER,REDO_COUNTER} from '../actions';
const rootReducer=combineReducers({
counter:undoable(counter,{
filter:includeAction([INCREMENT_COUNTER,DECREMENT_COUNTER]),
limit:10,
debug:true,
undoType:UNDO_COUNTER,
redoType:REDO_COUNTER
})
});
export default rootReducer;
import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../actions';
export default function counter(state=0,action) {
switch (action.type) {
case INCREMENT_COUNTER:
return state + 1;
case DECREMENT_COUNTER:
return state - 1;
default:
return state;
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import Counter from './containers/Counter';
import rootReducer from './reducers';
const store = createStore(rootReducer,applyMiddleware(thunk));
const rootEl = document.getElementById('root');
ReactDOM.render(
<Provider store={store}>
<Counter />
</Provider>, rootEl);
为什么老是报错 Cannot read property 'length' of undefined
const store = createStore(rootReducer,
);