最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncontrolled input React Hooks - Stack Overflow

programmeradmin8浏览0评论

I've started learing about react-hooks with a simple tutorial and to my surprise I got an error that I cannot figure out:

Warning: A component is changing an uncontrolled input of type text 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.

After this error, my component disappears but I still can input data that will correctly print out in console.

I've tried setting initial state for inputs and changing

setInputs(inputs => ({
  ...inputs, [event.target.name]: event.target.value
}));

to

setInputs({...inputs, [event.target.name]: event.target.value});

but I'm still getting error.

JSX

import React from 'react';
import './styles/form.scss';
import useSignUpForm from './hooks/customHooks.jsx';

const Form = () => {

    const {inputs, handleInputChange, handleSubmit} = useSignUpForm();

    return (
        <React.Fragment>
            <div className="formWrapper">
                <h1 className="header">Form</h1>
                <form onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label htmlFor="nicknameInput">Nickname</label>
                        <input type="text" id="nicknameInput" name="nickname" onChange={handleInputChange}
                               value={inputs.nickname} required/>

                        <label htmlFor="emailInput">Email Address</label>
                        <input type="text" id="emailInput" name="email" onChange={handleInputChange}
                               value={inputs.email} required/>

                        <label htmlFor="lastName">Last Name</label>
                        <input type="text" id="lastName" name="lastName" onChange={handleInputChange}
                               value={inputs.lastName} required/>
                    </div>
                    <button type="submit" className="btn btn-primary">Submit</button>
                </form>
            </div>
        </React.Fragment>
    )
};

export default Form;


Hooks

import React, {useState} from 'react';

const useSignUpForm = (callback) => {
    const [inputs, setInputs] = useState({});
    console.log(inputs);

    const handleSubmit = (event) => {
        if (event) {
            event.preventDefault();
        }
    };

    const handleInputChange = (event) => {
        event.persist();
        setInputs(inputs => ({
                ...inputs, [event.target.name]: event.target.value
            })
        );
    };

    return {
        handleSubmit,
        handleInputChange,
        inputs
    };

};

export default useSignUpForm;

Any ideas what causes this error?

I've started learing about react-hooks with a simple tutorial and to my surprise I got an error that I cannot figure out:

Warning: A component is changing an uncontrolled input of type text 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.

After this error, my component disappears but I still can input data that will correctly print out in console.

I've tried setting initial state for inputs and changing

setInputs(inputs => ({
  ...inputs, [event.target.name]: event.target.value
}));

to

setInputs({...inputs, [event.target.name]: event.target.value});

but I'm still getting error.

JSX

import React from 'react';
import './styles/form.scss';
import useSignUpForm from './hooks/customHooks.jsx';

const Form = () => {

    const {inputs, handleInputChange, handleSubmit} = useSignUpForm();

    return (
        <React.Fragment>
            <div className="formWrapper">
                <h1 className="header">Form</h1>
                <form onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label htmlFor="nicknameInput">Nickname</label>
                        <input type="text" id="nicknameInput" name="nickname" onChange={handleInputChange}
                               value={inputs.nickname} required/>

                        <label htmlFor="emailInput">Email Address</label>
                        <input type="text" id="emailInput" name="email" onChange={handleInputChange}
                               value={inputs.email} required/>

                        <label htmlFor="lastName">Last Name</label>
                        <input type="text" id="lastName" name="lastName" onChange={handleInputChange}
                               value={inputs.lastName} required/>
                    </div>
                    <button type="submit" className="btn btn-primary">Submit</button>
                </form>
            </div>
        </React.Fragment>
    )
};

export default Form;


Hooks

import React, {useState} from 'react';

const useSignUpForm = (callback) => {
    const [inputs, setInputs] = useState({});
    console.log(inputs);

    const handleSubmit = (event) => {
        if (event) {
            event.preventDefault();
        }
    };

    const handleInputChange = (event) => {
        event.persist();
        setInputs(inputs => ({
                ...inputs, [event.target.name]: event.target.value
            })
        );
    };

    return {
        handleSubmit,
        handleInputChange,
        inputs
    };

};

export default useSignUpForm;

Any ideas what causes this error?

Share Improve this question edited Jun 6, 2019 at 20:08 Daniel Bank 3,8993 gold badges43 silver badges55 bronze badges asked Jun 6, 2019 at 17:54 sienki_jenkisienki_jenki 1111 silver badge9 bronze badges 1
  • 1 FYI, those are controlled and not uncontrolled inputs. – Fellow Stranger Commented Aug 15, 2019 at 15:26
Add a comment  | 

2 Answers 2

Reset to default 16

You are getting the error, because your inputs start their life as undefined and then have a value. If you replace this const [inputs, setInputs] = useState({}); with this:

const [inputs, setInputs] = useState({
   nickname: '',
   lastname: '',
   email: ''
});

it will go away.

my favorite way of handling controlled inputs in react hooks is this syntax.. Make seperate state for each input you are trying to handle and then inside the onChange just call the setInput

onChange={e => setInput(e.target.value)}

the reason why you have an error is because the initial state is just an empty object, if you wanted to do it that way you would have to change your state to.

const [inputs, setInputs] = useState({
   nickname: '',
   lastname: '',
   email: ''
});
发布评论

评论列表(0)

  1. 暂无评论