简单的React计数器不起作用,console.log useState变量也不能吗?

时间:2019-07-06 12:26:45

标签: javascript reactjs typescript

我对React还是很陌生(一个月前才开始学习),并且我试图在页面上显示一个简单的计数器,但它只会更新一次。另外,每当我console.log() useState变量时,它们始终为空,但是由于我将它们添加到页面上的输出中,因此我可以看到它们正在更新,但是仍然无法console.log这些值?是什么赋予了?我一定做错了,但看不出原因。

这是codesandbox中“问题”的演示。

这是代码:

import React, { useState } from "react";

import "jqwidgets-scripts/jqwidgets/styles/jqx.base.css";
import JqxInput from "jqwidgets-scripts/jqwidgets-react-tsx/jqxinput";

const MyForm2: React.FC = () => {
  const [count, setCount] = useState(0);
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");

  const onEmailChange = (e?: any) => {
    setCount(count + 1);
    setEmail(e.args.value);
    console.log('You typed: ' + e.args.value);
    console.log("name: " + name + ", email: " + email);
  };

  const onNameChange = (e?: any) => {
    setCount(count + 1);
    setName(e.args.value);
  };

  return (
    <div>
      Name:{" "}
      <JqxInput value={name} onChange={(e: any) => setName(e.args.value)} />
      Email: <JqxInput value={email} onChange={onEmailChange} />
      <p>Count: {count}</p>
      <p>email: {email}</p>
      <p>name: {name}</p>
    </div>
  );
};

export default MyForm2;

谢谢。我期待发现我的壮观错误:-)

2 个答案:

答案 0 :(得分:1)

当下一个状态取决于上一个状态时,您应该将函数更新程序作为参数传递给setState。因此更改为:

setCount((count) => count + 1)

答案 1 :(得分:1)

Javascript ClosuresonNameChange的作用域对count变量关闭:

const MyForm2: React.FC = () => {
  const [count, setCount] = useState(0);
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');

  const onEmailChange = (e?: any) => {
    setCount(prev => prev + 1);           // <-- no closure, use previous state
                                          // Render as expected.
    setEmail(e.args.value);
  };

  const onNameChange = (e?: any) => {
    setCount(count + 1);                  // <-- `count` always 0;
                                          // Will always redner the value '1'.
    setName(e.args.value);
  };

  return (
    <div>
      Name: <JqxInput value={name} onChange={onNameChange} />
      Email: <JqxInput value={email} onChange={onEmailChange} />
      <p>Count: {count}</p>
    </div>
  );
};

Edit Q-56914083-Closures