【发布时间】:2020-05-31 11:42:17
【问题描述】:
我在我的状态下对 Redux 有一个小问题,我需要能够在两个 Reducer 中修改我的计数器属性,因为它对两个 reducer 的值更新(增量,减量)抱歉,我是 Redux 的新手,并尝试理解这个概念。
计数器组件
return(
<>
<div className="flex justify-center">
<div className='font-bold text-4xl text-blue-600 bg-gray-300 p-6 m-3 rounded-full'>The Result :
{this.props.counter}
</div>
</div>
<section className='flex p-5 m-3 justify-center'>
<button onClick={this.props.increment} className={`bg-green-400 ${btnDefault}`} >Increment</button>
<button onClick={() => this.props.decrement(this.props.counter)} className={`bg-red-400 ${btnDefault}`}>Decrement</button>
</section>
</>
)
}
}
const mapStateToProps = state => {
return {
counter: state.incReducer.counter,
}
};
const mapDispatchToProps = dispatch => {
return {
increment: () => dispatch(counterAction('INCREMENT')),
decrement: (counter) => dispatch(counterAction('DECREMENT',counter))
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter)
增量减速器
const initialState = {
counter: 0,
};
const reducer = (state = initialState, action) => action.type === actionType.INCREMENT ?
{
...state,
counter: state.counter + 1
}
: state;
export default reducer;
递减器
const initState = {
};
const reducer = (state = initState, action) => action.type === actionType.DECREMENT ?
{
...state,
counter: action.counter - 1
}
: state;
export default reducer;
Index.js
const reducer = combineReducers({
incReducer,
decReducer
});
const store = createStore(reducer);
ReactDOM.render(<Provider store={store}><App/></Provider> , document.getElementById('root'));
【问题讨论】:
-
您不应该在多个 reducer 中复制相同的值。一个 store 值只能在一个地方,即在一个 reducer 中定义和修改。
标签: reactjs redux react-redux