我是 ReactJS 新手,我对 React 函数有一些问题。我有一个简单的计数器,可以根据您单击的按钮更改当前数字。除了检查最小值和最大值之外,它工作正常。这是我的代码:
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>
)
}
这是应用程序组件:
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
}
您只需从 set
返回 cnt
即可。
在set
中,您将cnt
设置为所需的值,但没有返回任何内容,因此未定义
。在 decrease
和 increase
中,您将 cnt
设置为返回 set
的值,该值是未定义的
因此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 - 函数中的 React useState 方法无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57627057/