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

Accessing a value of a gotten from a function from outside the function

我有下面的一段代码,我在访问函数外的 BMI 时遇到问题,因为它 return 未定义。 单击 'calculate' 按钮时,函数本身应该 return BMI 的解决方案。我需要从函数范围之外访问 BMI 值,但它保持 returning 未定义。它已经在函数之外定义,所以我不确定它为什么会起作用。 我实际上找到了解决该问题的方法,但生成的代码看起来并没有优化。

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)

这里有两个问题。

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

第二个是 React 组件仅在 prop 或 state 更改时重新渲染。您需要将 BMI 变量保存为状态,以便组件重新呈现并显示更新后的 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';