此函数接受参数{values},并应计算结果并设置其状态(在ReactJS中(。setResult((不会向控制台输出任何内容,但是,console.log都会输出Nan、无效日期、使我的React应用程序崩溃,然后输出正确的值。
const [calcResult, setResult] = useState();
const calculator = (values) => {
let resultSeconds = (values.fileSize*1000)/(values.downloadSpeed/8);
let secondsPure = new Date(null);
secondsPure.setSeconds(resultSeconds);
console.log(secondsPure);
console.log(resultSeconds);
let result = secondsPure.toISOString().substr(11,8);
setResult(result);
console.log(result);
};
例如,让我们假设secondsPure=80。相应的console.log(secondsPure(将打印NaN,然后在React应用程序崩溃后,它将向控制台打印80。
数值示例:
downloadSpeed: "300"
fileSize: "3"
setState是异步函数,这意味着当您执行类似的操作时
const [result , setResult]=useState(null)
const calculator = (values) => {
setResult(result);
console.log(result);//this will output null because setResult call is not done yet
//when setResult finishes you component reloads and only then you can get the new value
};
如果要获得更新的值,则需要使用useEffect
并将result
设置为依赖
useEffect(() => {
console.log(result)
}, [result])