【发布时间】:2021-04-28 04:11:49
【问题描述】:
在输入字段中输入数字后,计数状态应该反映输入值,当我点击+或-,计数状态应该是加减法。
现在输入的输入值显示在 DOM 上,但它并没有改变 计数状态,当我点击 + 时,它没有按我的意愿工作。
操作如下:
export const incrementCount = () => {
return { type: INCREMENT };
};
export const decrementCount = () => {
return { type: DECREMENT };
};
export const resetCount = () => {
return { type: RESET }
};
export const typeCount = (number) => {
return {
type: TYPECOUNT,
payload: number
}
}
export const evenCount = () => {
return {
type: EVENCOUNT
}
}
export const oddCount = () => {
return { type: ODDCOUNT }
}
这里是减速器:
export default (state = 0, action) => {
switch (action.type) {
case INCREMENT:
return state + 1
case DECREMENT:
return state - 1
case RESET:
return state = 0
case TYPECOUNT:
return state = action.payload
case EVENCOUNT:
return state + 1
case ODDCOUNT:
return state + 1
default:
return state;
}
};
这是商店:
import count from "./count";
import { combineReducers } from "redux";
export default combineReducers({ count });
这是 Counter.js 从“反应”导入反应;
const Counter = ({
value,
onIncrement,
onDecrement,
onReset,
onType,
onEven,
onOdd
}) => {
return (
<div>
<p>value: {value}</p>
<p>
<button onClick={onIncrement}>+</button>
<button onClick={onDecrement}>-</button>
<button onClick={onReset}>Reset</button>
<input onChange={onType} type="number" value={value} />
<button onClick={onEven}>Even Count</button>
<button onClick={onOdd}>Odd count</button>
</p>
</div>
)
}
export default Counter;
这是 CounterContainer.js
import { useSelector, useDispatch } from "react-redux"
import Counter from "../components/Counter"
import { incrementCount, decrementCount, resetCount, typeCount, evenCount, oddCount } from "../actions/counterActions"
const CounterContainer = () => {
const count = useSelector(state => state.count)
const dispatch = useDispatch()
const increment = () => {
dispatch(incrementCount())
}
const decrement = () => {
dispatch(decrementCount())
}
const reset = () => {
dispatch(resetCount());
}
const type = ({ target }) => {
dispatch(typeCount(target.value))
}
const even = () => {
if(count % 2 === 0) {
dispatch(evenCount())
}
}
const odd = () => {
if(count % 2 === 1) {
dispatch(oddCount())
}
}
return (
<React.Fragment>
<Counter
value={count}
onIncrement={increment}
onDecrement={decrement}
onReset={reset}
onType={type}
onEven={even}
onOdd={odd}
/>
</React.Fragment>
)
}
export default CounterContainer
【问题讨论】:
-
如果我的回答很有帮助且内容丰富,那么我邀请您也请投票。干杯。
标签: reactjs input redux react-redux reducers