javascript - 函数中的 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
. 任何帮助,将不胜感激。
解决方案
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
是.
undefined
NaN
做同样事情的另一种方法:
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
}
推荐阅读
- javascript - 按下后退按钮时重新加载页面(移动设备,野生动物园)
- python - 如何在python中组合元组
- html - HTML - 在 div 容器中插入文本
- sql - 如何在postgresql中第4次出现字符之前切断字符串?
- amazon-web-services - AWS Application Load Balancer - 重定向一小部分流量
- php - 在 AMPPS 上安装 php 扩展
- laravel-5 - Vue自定义输入文件组件无法正确提交
- mysql - 在bash中将stdout重定向到mysql
- angular - 我正在尝试在同一家商店中选择三个州,但我遇到了问题
- ios - 点击文本字段时获取表格视图部分索引