我应该忽略React警告:输入元素不应该从不受控制的状态切换到受控制的状态吗? [英] Should I ignore React warning: Input elements should not switch from uncontrolled to controlled?

查看:269
本文介绍了我应该忽略React警告:输入元素不应该从不受控制的状态切换到受控制的状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

警告:组件正在更改要控制的类型为时间的不受控制的输入.输入元素不应从不受控制的状态切换到受控制的状态(反之亦然).在组件的生命周期中决定使用受控还是不受控制的输入元素.

因此,我有一个组件,可以根据数组中的项目动态呈现多个输入字段.我的数组包含7天,并且每天循环输入多个字段.这些输入字段中的每一个都有一个动作.通过单击按钮,我可以选择某些输入字段是否需要具有相同的内容或不同的内容.这些输入字段中的每个字段也都需要具有唯一的状态.因此,我创建了一个空状态,如下所示:

So I have a component that renders multiple input fields dynamically based on items in a array. My array contains the 7 days and I loop multiple input fields for each day. There is also an action for each of these input fields. By clicking on a button I can choose if some input fields need to have the same content or different content. Each of these input fields also need to have a unique state. So, I create an empty state like this:

constructor(props) {
        super(props);
        this.state = {};
    }

并在我的循环中创建它,如下所示:

And create it inside my loop like this:

() => this.setState({ ['show' + day + '_morning'] : true })
() => this.setState({ ['show' + day + '_afternoon'] : true })

尽管我可以将每个状态预定义为'showMonday_morning'等.我试图避免使用它,因为我想学习如何动态创建循环状态以供将来参考.

一切正常,但我从上面收到错误代码.

Although I could predefine each of these states as 'showMonday_morning', etc.. I tried to avoid it because I want to learn how to create states dynamically in loops for future reference.

Everything works perfectly but I receive the error code from above.

我可以掉以轻心这个错误还是应该解决?如果必须解决该问题,该如何在循环内动态创建和添加状态并避免出现此错误?

Can I take this error lightly or should this be solved? In case it has to be solved, how can I create and add states dynamically inside a loop and avoid this error?

推荐答案

您不需要在构造函数中动态创建状态.相反,您可以有条件地在渲染中使用它.

You don't need to create state in constructor dynamically. Rather you could just conditionally use it in render.

<input value={this.state.['showSatMorning'] || ''} />

我可以掉以轻心还是要解决这个错误?

Can I take this error lightly or should this be solved?

尽管此警告不会影响您应用中的任何内容,但最好处理此类警告以使您的应用保持一致并避免意外问题

Although this warning wouldn't affect anything in your App but its better to handle such warnings to keep your app consistent and avoiding unexpected issues

这篇关于我应该忽略React警告:输入元素不应该从不受控制的状态切换到受控制的状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆