在我的例子中,我有兩個按鈕「增量」和「減量」。我想顯示增加按鈕被點擊時會增加的數字。當點擊減量按鈕時遞減 。如何使用react和redux遞增和遞減值?
這裏是我的代碼 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'));
是那些爲你工作的進口? – therewillbecode
在這裏尋找與Redux有關的todo應用程序示例以及變量名稱的靈感。 http://redux.js.org/docs/basics/ExampleTodoList.html – therewillbecode
@ user944513不會添加react-native標籤來反應只有問題。 –