从函数外部访问从函数获取的值



我有下面的一段代码,在访问函数外的BMI时遇到问题,因为它返回未定义。单击"计算"按钮时,函数本身应返回BMI的解决方案。我需要从函数范围之外访问BMI值,但它一直返回未定义的值。它已经在函数外定义了,所以我不确定它为什么会出错。事实上,我找到了解决问题的方法,但最终的代码看起来并没有得到优化。

const { weight, height } = userInput;
/**Calculate the BMI and round to two decimal places */
let BMI;
const calculateBMI = () => {
BMI = weight / (height * height);
console.log(BMI); //logs the value of BMI onClick of the button
return BMI;
//let BMIValue = Math.round(BMI * 100) / 100;
//return BMIValue;
};
console.log(BMI); //logs undefined regardless
return (
<div>
<div>
<label htmlFor="height">Height:</label>
<input
type="number"
name="height"
onChange={handleChange}
value={userInput.height}
/>
</div>
<div>
<label htmlFor="weight">Weight:</label>
<input
type="number"
name="weight"
onChange={handleChange}
value={userInput.weight}
/>
</div>
<button onClick={calculateBMI}>
Calculate
</button>
</div>
);

如果您想在用户交互后同步UI中的数据,那么您应该使用useState(这实际上是一个强大的用例(。

所以你应该试试


const [BMI, setBMI] = useState();
const calculateBMI = () => {
currentBMI = weight / (height * height);
setBMI(currentBMI);
};
console.log(BMI)

这里有两个问题。

首先,calculateBMI()之外的console.log()虽然在函数之后定义,但实际上是在函数之前运行的,因为函数仅在单击事件时调用。因此,它将始终记录undefined

第二种是react组件仅在道具或状态更改时重新渲染。您需要将BMI变量保存为state,以便组件重新渲染并显示更新的BMI(如果这是该组件的用途(。

要调试此项并在单击后显示BMI值更新,请尝试使用useState挂钩并使用将值打印到屏幕上

const [BMI, setBMI] = useState(undefined);
const calculateBMI = () => {
setBMI(weight / (height * height));
return BMI;
};
return (
<div>
<div>
<label htmlFor="height">Height:</label>
<input
type="number"
name="height"
onChange={handleChange}
value={userInput.height}
/>
</div>
<div>
<label htmlFor="weight">Weight:</label>
<input
type="number"
name="weight"
onChange={handleChange}
value={userInput.weight}
/>
</div>
<button onClick={calculateBMI}>
Calculate
</button>
{BMI}
</div>
);

不要忘记在文件顶部导入useState,可能使用类似的东西

import React, { useState } from 'react';

最新更新