javascript - 组件正在将文本类型的受控输入更改为不受控 - ReactJS

标签 javascript arrays reactjs object controlled-component

我有一个页面,我从服务器获取数据并为受控输入设置状态值。 (例如,我的输入的值为 this.state.name,我从服务器获取名称,例如 Dave,并将其设置为状态名称,因此输入的值为 Dave。它可以工作,但我得到了对象数组的问题

这就是状态

this.state = {
        ingredients: [{ ingredient: "", quantity: '' }],
        //other properties
   }

这就是我使用成分的方式

{this.state.ingredients.map(({ ingredient, quantity }, index) => (


   <div key={index}>
        ingredient: <input value={ingredient} className="ingredientClass" type="text" autoComplete="off" placeholder="e.g: pepper" onChange={{e => this.update(index, "ingredient", e.target.value)} />
        quantity: <input value={quantity} autoComplete="off" type="text" placeholder="e.g: 1g" onChange={e => this.update(index, "quantity", e.target.value)} />
        <button onClick={this.BtnClick}>delete</button> <br />
       {this.state.errorFor === 'ingredientsfield' ? this.state.errmsg : null}
   </div>
))}

但这会导致此错误:

Warning: A component is changing a controlled input of type text 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. More info: link

为什么会发生这种情况?我该如何修复它?

P.S:我检查过,配料已成功从服务器获取

更新:onChange事件的代码

update(index, key, value) {
    this.setState(({ ingredients }) => ({ ingredients: ingredients.map((ing, i) => i === index ? { ...ing, [key]: value } : ing) }));
    console.log(this.state.ingredients)
}

最佳答案

问题是其中一个输入在某个时刻具有未定义或空值。

我无法理解是什么将您显示的代码中的输入值更改为 null(未定义)。但是您可以使用 ReactDevTools 来观察应用程序运行期间输入的值。

关于javascript - 组件正在将文本类型的受控输入更改为不受控 - ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56916023/

相关文章:

javascript - 通过行单击事件传递动态创建的 html 表格行innertext id

javascript - Python 返回上一页并记住元素

C# 字节数组转换为 VB.NET

javascript - 按值或值组比较数组

javascript - 使用javascript从维基百科html表行中提取数组

reactjs - 编译器警告 "Module not found: Error: Can' t resolve './locale' “因为我在我的 React 应用程序中使用了 momentjs

javascript - 在 EditorGridPanel 中显示组件而不单击

javascript - 使用传播运算符 react 添加项目

使用 React Router 路由到另一个组件时 CSS 没有改变

javascript - AngularJS:在列和行上带有 ng-repeat 的表