在我的例子中,我有两个按钮"增量"和"减少"。我想显示单击增量按钮时将增加的数字。和 单击减量按钮时递减。
这是我的代码 https://plnkr.co/edit/UwQjdyRJhz4H3orUc3m5?p=preview
const { createStore, bindActionCreators, applyMiddleware,combineReducers } = Redux;
const { Provider, connect } = ReactRedux;
const thunk = window.ReduxThunk.default;
const abc = (state = {}, action) => {
switch (action.type) {
case 'SET_DATA':
return action.payload;
default:
return state;
};
};
const pqr = (state = 0,action) => {
console.log('in redux', action.type)
switch(action.type){
case 'INC':
return state +1
case 'DEC':
return state -1
default :
return state;
}
}
const cmpbind = combineReducers({
abc,
pqr
})
const store = createStore(cmpbind, applyMiddleware(thunk));
class First extends React.Component {
constructor (props){
super(props);
this.getData = this.getData.bind(this);
}
getData(){
this.props.load();
}
inc (){
console.log('ince', this.props)
this.props.increment();
}
dec (){
console.log('dec')
this.props.decrement();
}
render() {
return (
<div>
<button onClick={this.getData}>GET DATA</button>
<pre>{JSON.stringify(this.props.data)}</pre>
<button onClick={this.inc.bind(this)}>INCREMENT</button>
<p>{this.props.digit}</p>
<button onClick={this.dec.bind(this)}>DECREMENT</button>
</div>
);
}
}
const actions = {
load: () => {
return (dispatch) => {
return axios.get('data.json').then((response) => {
dispatch({
type: 'SET_DATA',
payload: response.data,
});
});
};
},
increment: () => {
return {
type: 'INC',
}
},
decrement: () => {
return {
type: 'DEC',
}
}
};
const mapStateToProps = (state) => ({
data: state
});
const mapDispatchToProps = (dispatch) => ({
load: bindActionCreators(actions.load, dispatch),
});
const AppContainer = connect(mapStateToProps, mapDispatchToProps)(First);
ReactDOM.render(
<Provider store={store}>
<AppContainer/>
</Provider>
,document.getElementById('root'));
答案 0 :(得分:1)
您需要更改mapStateToProps
和mapDispatchToProps
功能,以便从缩减器和
const mapStateToProps = (state) => ({
data: state.abc,
digit: state.pqr
});
const mapDispatchToProps = (dispatch) => ({
load: bindActionCreators(actions.load, dispatch),
increment: bindActionCreators(actions.increment, dispatch),
decrement: bindActionCreators(actions.decrement, dispatch)
});
<强> PLNKR 强>
答案 1 :(得分:1)
最简单的方法是将mapDispatchToProps
更改为:
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(actions, dispatch),
});
并且您的onClick
听众可以更改为:
getData(){
this.props.actions.load();
}
inc (){
console.log('ince', this.props)
this.props.actions.increment();
}
dec (){
console.log('dec')
this.props.actions.decrement();
}