【问题标题】:React hook to initial state - React native反应钩子到初始状态 - 反应原生
【发布时间】:2020-02-05 22:26:07
【问题描述】:

我目前正在响应 Hooks 并有以下问题,每次按下按钮时,这个简单的代码都会递增。当计数达到 2 时,我创建了一个记录“已完成”的条件。但是我无法将计数恢复为 0。

非常感谢您

这是我的代码:

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  if(count =='2'){
    console.log('finished')
    //count = 0
  }
  return (
    <div>
      <p>clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click here
      </button>
    </div>
  );
}

【问题讨论】:

  • setCount(0)??

标签: reactjs react-native react-hooks


【解决方案1】:

您需要使用setCount方法将其设置回0

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  if(count === 2){
    console.log('finished')
    setCount(0);
  }
  return (
    <div>
      <p>clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click here
      </button>
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多