【问题标题】:Why is my increment count button returning [Object object]为什么我的增量计数按钮返回 [Object object]
【发布时间】:2020-05-23 11:15:50
【问题描述】:

我正在尝试学习 React 钩子,并且正在尝试编写一个增加计数状态的简单函数。

import React, { useState } from "react";

export const HookCounter = () => {
    const [count, setCount] = useState(0);

    const incrementCount = (count) => {
        setCount(count + 1);
    };

    return (
        <div>
            <button onClick={incrementCount}>Press me!</button>
            <h1>
                You have pressed the button <strong>{count}</strong> times
            </h1>
        </div>
    );
};

但是,当我单击按钮时。而不是像我希望的那样增加计数器。我看到的是:

You have pressed the button [object Object]1 times.

这是为什么?

【问题讨论】:

    标签: reactjs react-hooks use-state


    【解决方案1】:

    它不能正常工作的原因是,你已经将 count 定义为一个参数,它实际上是一个来自 onClick 的事件

    函数不是从闭包中获取计数,而是从参数中获取它,因为它优先。当您尝试执行count + 1 时,由于事件是一个对象,它会将事件对象字符串化并为其添加 1,从而为您提供[object Object]1

    import React, { useState } from "react";
    
    export const HookCounter = () => {
        const [count, setCount] = useState(0);
    
        const incrementCount = () => { // no count argument here
            setCount(count + 1);
        };
    
        return (
            <div>
                <button onClick={incrementCount}>Press me!</button>
                <h1>
                    You have pressed the button <strong>{count}</strong> times
                </h1>
            </div>
        );
    };
    

    【讨论】:

      【解决方案2】:

      @Khatri 是对的,当您收到 count 作为参数时,它会获取该按钮的事件对象。您可以使用console.log打印计数(我将其重命名为事件)来检查它。

      import React, { useState } from "react";
      
      export const HookCounter = () => {
          const [count, setCount] = useState(0);
      
          const incrementCount = (event) => {
              console.log(event, 'event');
              setCount(count+1);
          };
      
          return (
              <div>
                  <button onClick={incrementCount}>Press me!</button>
                  <h1>
                      You have pressed the button <strong>{count}</strong> times
                  </h1>
              </div>
          );
      };
      

      【讨论】:

        猜你喜欢
        • 2011-07-13
        • 2011-10-24
        • 1970-01-01
        • 2020-05-24
        • 1970-01-01
        • 2021-01-29
        • 1970-01-01
        • 1970-01-01
        • 2011-05-22
        相关资源
        最近更新 更多