M
M
MarEeeeeee2020-12-23 10:25:19
React
MarEeeeeee, 2020-12-23 10:25:19

How to fix the error "Component changes uncontrolled input to control"?

There is the following component, which, when the application is running, links an error. Everything seems to be working, how to remove the error and why does it appear?

import React from 'react'
import {connect} from "react-redux"
import {createNewUser, deleteUser, changeInfo, userInfo} from "../components/redux/action"

//классовый компонент.
class SecondWindow extends React.Component{
    constructor(props){
        super(props);
    }
    
    
    handleOptionChange = e => {
        this.setState(
            {
                selectedOption:e.target.value
            }
        )
    }

    submitHandler = e => {
        e.preventDefault();    
        const newUser = {
            id: Date.now().toString(),
            FIO: "Имя",
            position:"Должность",
            birthDay: "год/месяц/день",
            sex: true,
            fired: false
        };        
        this.props.createNewUser(newUser); // создаем нового пользователя
        this.props.userInfo(newUser); // закватывает текущего юзера для работы в форме
        this.props.setActive(this.props.items.items.length); // добавляем выделение на нового пользователя
        
    }

    changeInputHandler = ({ target: t }) => {
        this.setState(state => ({
          ...state,
          [t.name]: t.type === 'checkbox' || t.type === "radio"  ? t.checked : t.value,
          
        }));
        
        
        let newValue;
        if(t.type === "radio"){
            newValue = !this.props.items.activeUser.sex;
        }else{
            newValue = t.type === 'checkbox'  ? t.checked : t.value;
        }
                
        const valueForUpdate = {
            id: this.props.items.activeUser.id,
            box: t.name,
            newValue: newValue 
        };        
        this.props.changeInfo(valueForUpdate);
      }

    deleteUser = () => {        
        this.props.deleteUser(this.props.items.activeUser);        
    }
    

    render() {
        return (
            <form onSubmit={this.submitHandler}>
                <div className="input-group mb-3">                    
                    <input type="text" className="form-control" placeholder="ФИО"
                    name="FIO" 
                    onChange={this.changeInputHandler}
                    value={this.props.items.activeUser.FIO}
                    maxLength="15"></input>
                </div>
                <select className="form-select" aria-label="Default select example"
                name ="position"
                onChange={this.changeInputHandler}
                value={this.props.items.activeUser.position}                
                >                    
                    <option value = "Не назначено">Не назначено</option>
                    <option value="Старший разработчик">Старший разработчик</option>
                    <option value="Младший разработчик">Младший разработчик</option>
                    <option value="Эйчар">Эйчар</option>
                    <option value="Уборщик">Уборщик</option>
                </select>

                <div className="form-group ">                
                    <div className="mb-3"></div>
                        <input className="form-control" type="date"  id="example-date-input"
                        name ="birthDay"
                        onChange={this.changeInputHandler}
                        value={this.props.items.activeUser.birthDay}></input>  
                </div>
              


               
                <div className="form-check">
                    <input className="form-check-input" type="radio" 
                     id="flexRadioDefault1"
                     
                     name ="sex"
                     onChange={this.changeInputHandler}
                     checked = {this.props.items.activeUser.sex}
                    ></input>
                    <label className="form-check-label" htmlFor="flexRadioDefault1">
                    М
                    </label>
                </div>
                <div className="form-check">
                    <input className="form-check-input" type="radio" 
                    id="flexRadioDefault1"
                    
                    name ="sex"
                    onChange={this.changeInputHandler}
                    checked = {!this.props.items.activeUser.sex}
                    
                    ></input>
                    <label className="form-check-label" htmlFor="flexRadioDefault1">
                    Ж
                    </label>
                
                </div>
                
                
                
                <div className="form-check">
                    <input className="form-check-input" type="checkbox"  id="flexCheckDefault"
                    name ="fired"
                    onChange={this.changeInputHandler}
                    checked={this.props.items.activeUser.fired}
                    
                    ></input>
                    <label className="form-check-label" htmlFor="flexCheckDefault">
                    Уволен
                    </label>
                </div>
                <button type="button" className="btn btn-success" onClick = {this.submitHandler}                 
                 >Добавить нового сотрудника</button>
                <button type="button" className="btn btn-danger"
                 onClick = {this.deleteUser}
                 disabled = {Object.keys(this.props.items.activeUser).length===0 ? true : false}
                 >Удалить выбранного сотрудника</button>  
            </form>
        );
    }
}

const mapStateToProps = state => {    
    return {
        items: state.items,
    }
}

const mapDispatchToProps = {
    createNewUser: createNewUser,
    deleteUser:deleteUser,
    changeInfo:changeInfo,
    userInfo: userInfo
}

export default connect(mapStateToProps, mapDispatchToProps)(SecondWindow);

mistake

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
    at input
    at div
    at form
    at SecondWindow (http://localhost:3000/static/js/main.chunk.js:522:5)
    at Connect(SecondWindow) (http://localhost:3000/static/js/0.chunk.js:33750:75)
    at div
    at div
    at App (http://localhost:3000/static/js/main.chunk.js:55:76)
    at Provider (http://localhost:3000/static/js/0.chunk.js:33463:20)
console.<computed> @ index.js:1
printWarning @ react-dom.development.js:67
error @ react-dom.development.js:43
updateWrapper @ react-dom.development.js:1533
updateProperties @ react-dom.development.js:9376
commitUpdate @ react-dom.development.js:10252
commitWork @ react-dom.development.js:21401
commitMutationEffects @ react-dom.development.js:23401
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23121
unstable_runWithPriority @ scheduler.development.js:646
runWithPriority$1 @ react-dom.development.js:11276
commitRoot @ react-dom.development.js:22990
performSyncWorkOnRoot @ react-dom.development.js:22329
(anonymous) @ react-dom.development.js:11327
unstable_runWithPriority @ scheduler.development.js:646
runWithPriority$1 @ react-dom.development.js:11276
flushSyncCallbackQueueImpl @ react-dom.development.js:11322
flushSyncCallbackQueue @ react-dom.development.js:11309
discreteUpdates$1 @ react-dom.development.js:22420
discreteUpdates @ react-dom.development.js:3756
dispatchDiscreteEvent @ react-dom.development.js:5889

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question