【发布时间】:2020-04-24 20:29:08
【问题描述】:
我正在尝试做一个只接受正整数的输入。我也在寻找有关放置验证逻辑的任何提示(如果有更好的地方)。
现在,如果输入,我正在 onChange 内调度 redux 状态更改。这就是我验证价值的地方。
我有一个输入:
<input className='form-control' type='number' value={minors} onChange={ev => dispatch(updateMinors({
value: Number(ev.target.value) > -1 ? Number(ev.target.value) : 0,
isValid: !isNaN(ev.target.value) && Number.isInteger(ev.target.value),
wasValidated: true
}))} style={{ maxWidth: '6rem' }} />
这使用选择器连接到 redux 状态:
const minors = useSelector(state => state.minors.value)
我有一个相同的减速器:
updateMinors: (state, action) => {
state.minors.value = action.payload.minors
state.minors.isValid = action.payload.isValid
state.minors.wasValidated = action.payload.wasValidated
}
同一个 slice 的初始 redux 状态是:
minors: {
value: 0,
isValid: false,
wasValidated: false
}
使用此代码呈现的默认视图是:
<div class="input-group mb-1">
<input class="form-control" type="number" value="0" style="max-width: 6rem;">
<div class="input-group-append">
<span class="input-group-text" style="min-width: 5rem;">minors</span>
</div>
</div>
当我尝试使用退格键清除值时,我收到以下警告:
index.js:1 Warning: A component is changing a controlled input of type number to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
我知道还有另一种方法可以做到这一点,我正在努力解决。任何帮助将不胜感激!
更新
减速器action.payload.minor 有错字。应该是action.payload.value。
这导致在输入值中和undefined 赋值。
这反过来又将输入字段从 controlled 更改为 uncontrolled 并因此发出警告。
修正错字修正了警告。
【问题讨论】: