【问题标题】:Clearing input changes it from controlled to uncontrolled清除输入将其从受控变为不受控
【发布时间】: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 并因此发出警告。 修正错字修正了警告。

【问题讨论】:

    标签: html reactjs forms redux


    【解决方案1】:

    当您将 onChange 添加到输入时,React 会将其视为受控输入,并期望提供状态值,这就是您在代码中使用 value={minors} 所做的事情

    但是在你的 reducer 中,如果你将 Minor 更改为 nullundefined,那么 React 会认为你没有提供值,你会收到这条错误消息,说明你正在从受控变为不受控。

    这个bug来自你的reducer,你将state.minors.value分配给action.payload.minors,它应该是:

    updateMinors: (state, action) => {
      state.minors.value = action.payload.value
      state.minors.isValid = action.payload.isValid
      state.minors.wasValidated = action.payload.wasValidated
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-09
      • 2020-11-01
      • 2020-08-27
      • 2019-11-14
      • 1970-01-01
      • 2016-08-03
      • 2020-07-30
      • 2018-01-13
      相关资源
      最近更新 更多