1

这一定是一个关于 React 钩子的老问题,但我就是不明白为什么,我用只有基本知识的钩子来改变我的代码。下面的示例格式是带有条件语句的单独状态值,适用于我的输入表单,但是:

const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [userName, setUserName] = useState("");
const [error, setError] = useState(null);


const onChangeHandler = event => {
   const { name, value } = event.currentTarget;

   if (name === "userEmail") {setEmail(value)}
   else if (name === "userPassword") {setPassword(value)}
   else if (name === "userName") {setUserName(value)}
};

当我尝试像下面的示例那样将其置于单一状态时,它不起作用并直接转到错误消息:

const [newUser, setNewUser] = useState({
  userName: "",
  email: "",
  password: "",
  error: null,
});


const { userName, email, password, error } = newUser

const onChangeHandler = event => {
  const { name, value } = event.currentTarget;

  setNewUser({...newUser, [name]: value})
};

使用输入字段,它适用于单独的状态值,但不适用于多状态值,并且字段不可点击:

    <Form.Group>
      <Form.Control
        size="lg"
        type="text"
        placeholder="Username"
        name="userName"
        value={userName}
        onChange={event => onChangeHandler(event)}
        required
      />
    </Form.Group>
    
    <Form.Group> 
      <Form.Control
        size="lg"
        type="email"
        name="userEmail"
        placeholder="E-mail"
        value={email}
        onChange={event => onChangeHandler(event)}
        required
      />
    </Form.Group>

    <Form.Group>
      <Form.Control
        type={"password"}
        placeholder="Password"
        name="userPassword"
        value={password}
        onChange={event => onChangeHandler(event)}
        required
      />
    </Form.Group>
4

1 回答 1

1

你在混淆名字。在初始状态下,您有以下内容:

const [newUser, setNewUser] = useState({
  userName: "",
  email: "",
  password: "",
  error: null,
});

但是在更改值时,您将值设置为userName, userEmail, userPassword。正如下面的 JSX 中提到的,您添加了name每个字段的 prop。

让名称同步,您就可以开始了!

于 2020-08-11T09:55:18.290 回答