首页 > 解决方案 > 函数中的 React useState 方法无法按预期工作

问题描述

我是 ReactJS 的新手,我对反应功能有一些问题。我有一个简单的计数器,可以根据您单击的按钮更改当前数字。除了检查最小值和最大值外,它工作正常。这是我的代码:

import React, { useState } from 'react';

export default function CounterFunction(props) {

  const {min, max} = props;
  const [cnt, setCnt] = useState(min);

  const decrease = () => {
    setCnt(set(cnt - 1));
  }

  const increase = () => {
    setCnt(set(cnt + 1));
  }

  let set = function(newCnt) {
    console.log("TCL: set -> newCnt", newCnt)
    let cnt = Math.min(Math.max(newCnt, min), max);
    setCnt(cnt);
  }

  return (
    <div>
      <button onClick={decrease}>Minus 1</button>
      <strong>{cnt}</strong>
      <button onClick={increase}>Plus 1</button>
    </div>
  )
}

这是 App 组件:

import React from 'react';
import MinMaxFunction from './carts/minmax';

export default function() {
  return (
    <div>
      <MinMaxFunction min={2} max={10} />
    </div>
  );
}

当我尝试增加或减少数字时,它变成NaN. 任何帮助,将不胜感激。

标签: javascriptreactjs

解决方案


const decrease = () => {
  setCnt(set(cnt - 1));
}

const increase = () => {
  setCnt(set(cnt + 1));
}

let set = function(newCnt) {
  console.log("TCL: set -> newCnt", newCnt)
  let cnt = Math.min(Math.max(newCnt, min), max);
  return cnt;  // return
}

你只需cnt要从set.

set您设置cnt为所需值但因此不返回任何内容undefined。Indecrease并且increase您正在设置cnt返回值,因此set是. undefinedNaN


做同样事情的另一种方法:

const decrease = () => {
  set(cnt - 1); // call the set function, no need of setCnt here
}

const increase = () => {
  set(cnt + 1);
}

let set = function(newCnt) {
  console.log("TCL: set -> newCnt", newCnt)
  let cnt = Math.min(Math.max(newCnt, min), max);
  setCnt(cnt);  // set state just here
}

推荐阅读