Should I ignore React warning: Input elements should not switch from uncontrolled to controlled?

耗尽温柔 提交于 2019-12-11 11:36:27

问题


Error code

Warning: A component is changing an uncontrolled input of type time to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

Description

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 })

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.

Question

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?


回答1:


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




回答2:


Up to what I know, React.js is telling you to decide in using one type of Input elements, controlled or uncontrolled, if you have both of them in a component, you will be seeing that warning, I suggest to make a custom InputComponent where you can use it all along your React App.

This warning is not considered to be dangerous, it's for a cleaner React and optimization.



来源:https://stackoverflow.com/questions/53646594/should-i-ignore-react-warning-input-elements-should-not-switch-from-uncontrolle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!