React项目使用



我正在使用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;

希望这段代码能帮到你:

const counterReducer = (state = initialState, action) => {
if (action.type === 'increment') {
return {
...state,
counter: state.counter + 1
};
}
if (action.type === 'increase') {
return {
...state,
counter: state.counter + action.amount
};
}
if (action.type === 'decrement') {
return {
...state,
counter: state.counter - 1
};
}
if (action.type === 'toggle') {
return {
...state,
showCounter: !state.showCounter
};
}
return state;
};

之后,您应该检查分派类型中的错别字。decremenntincremennt.

试试这个代码:

const incrementHandler = () => {
dispatch({ type: 'increment', amount: 10 });
};
const increaseHandler = () => {
dispatch({ type: 'increase' });
};
const decrementHandler = () => {
dispatch({ type: 'decrement' });
};
const toggleCounterHandler = () => {
dispatch({ type: 'toggle' });
};

最新更新