我正在使用React构建UI,在这里我使用redux的增量和减量功能。不幸的是,我的增量和减量按钮不工作,可能是这个问题是由于一些逻辑错误。我将非常感谢,如果有人帮助我解决这个问题。在这里我张贴我的源代码。
**Creating Redux store code**
import {createStore} from 'redux';
const initialState ={counter:0, showCounter: true};
const counterReducer = (state =initialState,action) => {
if (action.type === 'increment') {
state.counter++;
return {counter: state.counter + 1,
showCounter: state.showCounter
};
}
if (action.type === 'increase') return{
counter: state.counter + action.amount,
}
if ( action.type ==='decrement'){
return {
counter: state.counter - 1,
};
}
if (action.type === 'toggle'){
return{
showCounter: !state.showCounter,
counter: state.counter
};
}
return state;
};
const store = createStore(counterReducer);
export default store;
**Counte.js code**
import {useDispatch, useSelector} from 'react-redux';
import classes from './Counter.module.css';
const Counter = () => {
const dispatch = useDispatch();
const counter = useSelector(state => state.counter);
const show = useSelector(state => state.showCounter);
const incrementHandler = () => {
dispatch({type:'incremennt', amount:10});
};
const increaseHandler = () => {
dispatch({type:'decrement'});
};
const decrementHandler = () =>{
dispatch({type:'decremennt'});
};
const toggleCounterHandler = () => {
dispatch({type:'toggle'})
};
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
{show && <div className={classes.value}>{counter}</div>}
<div>
<button onClick={incrementHandler}>Increment</button>
<button onClick={increaseHandler}>Increase by 10</button>
<button onClick={decrementHandler}>Decrement</button>
</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
</main>
);
};
export default Counter;
2条答案
按热度按时间pdkcd3nj1#
我希望这段代码可以帮助你:
之后,您应该检查派遣类型
decremennt
和incremennt
中的拼写错误。请尝试以下代码:
nbysray52#
检查以下内容: