【问题标题】:How to use the return value from React hook updater function?如何使用 React hook updater 函数的返回值?
【发布时间】:2021-07-30 15:13:36
【问题描述】:

我使用以下代码作为我的状态的更新函数(内部挂钩)。

虽然控制台输出在回调中正常工作,但我如何访问外部的值。我返回someStatus 并将其分配给x。但是x 打印为undefined

下面的代码有问题吗?

let x = setSomeStatus((someStatus) => {
    console.log("Some Status :::: :" + someStatus); // "XYZ"
    return someStatus;
});
console.log("x = " + x); // undefined

我按照建议在下面尝试了,但仍然没有在回调之外获得更新的值;

setSomeStatus((someStatus) => {
    console.log("File Status :::: :" + someStatus); // "XYZ"
    return someStatus;
});
console.log("someStatus = " + someStatus);

以下似乎可以正常工作(请确认它是否看起来不错)

const onCellClicked = (e) => {
        if (e.data.status !== 'TO') {
            console.log(e);
            //let fileStatus;
            let fileType = (e.data.status === 'Y') ? 'O' : 'I';
            setCurrentFileStatus(e.data.status);
            setFileType(fileType);

            var tempObj = {};
            setCurrentFileStatus((fileStatus) => {
                setFileType((fileType) => {
                    tempObj.currentFileStatus = fileStatus;
                    tempObj.summaryDate = form.dateField;
                    tempObj.fileType = fileType;
                });             
            });
            setSharedData(tempObj);
            console.log("tempObj = " + tempObj);
        }
    }

【问题讨论】:

  • 您将x 转换为一个函数,但您没有调用它。
  • setSomeStatus 是 setState 函数吗?如果是这样,为什么不直接访问状态而是尝试将x设置为它?
  • 如果我尝试调用它,我会得到 x 不是函数
  • 如果您将回调传递给 setState 函数,它接收的参数(在您的情况下为 someStatus)是之前的值。您返回相同的参数而不更改它,因此状态始终设置为相同的undefined 值。阅读我在答案中发布的链接中的Functional updates

标签: reactjs react-hooks


【解决方案1】:

假设setSomeStatusa setState function,你传递给 setState 的回调的 return 语句只会从回调中返回,并因此设置状态,但实际上不会从 setState 函数返回值。

反正你已经定义了一个状态,你不需要将它存储在一个单独的变量中(在你的例子中是x),你可以直接访问它。

const { useState } = React;

const App = () => {
  const [someState, setSomeState] = useState();

  return (
    <div>
      <p>Type something to change the state</p>
      <input
        onInput={(e) =>
          setSomeState((prev) => {
            console.log("changing the state from", prev, "to", e.target.value);
            return e.target.value;
          })
        }
      />
      <h2>The state is {someState}</h2>
    </div>
  );
};

// Render it
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

【讨论】:

  • 我仍然没有得到更新的值(用我尝试过的编辑过的原始问题)
  • 状态值(我的代码 sn-p 中的someState)始终具有更新的值。只要用useState钩子正确定义,就可以直接访问它
  • @copenndthagen 这是因为您在函数中返回旧状态值,因此新值始终是旧值。
  • 好的..我在原始问题中进行了一些更改并更新了...我得到了所需的输出...但是请您看看并确认更新的代码是否正确。 ..
  • 所以基本上我对 2 个状态变量中的每一个都有一个使用过的回调
猜你喜欢
  • 2021-07-21
  • 1970-01-01
  • 2020-08-23
  • 2020-10-28
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
相关资源
最近更新 更多