【问题标题】:set method in react hooks does not set the value [duplicate]react hooks中的set方法没有设置值[重复]
【发布时间】:2021-02-15 03:05:24
【问题描述】:
let [amount, setAmount] = React.useState(100);

function ChangeHandler(event) {
  let value = event.target.value;
  setAmount(value);
  props.update(amount);
}

props.update 是我从更高的组件传递来更新另一个 Hook 的函数。

【问题讨论】:

  • 你能补充更多细节吗?
  • 更新是异步的,更多在链接问题的答案和the documentationsetAmount 肯定会更新您的状态项。它不会更新函数可能关闭的范围内变量;你需要确保你的函数没有状态闭包。 (注意:声明你的状态成员时使用constconst [amount, setAmount] = React.useState(100);。它可以帮助你记住那个变量永远不会改变,改变是你得到的那个下一次 你打电话给useState。)

标签: javascript reactjs react-hooks


【解决方案1】:

在下一行设置后无法访问状态。

这样做

let [amount, setAmount] = React.useState(100);

function ChangeHandler(event) {
  let value = event.target.value;
  setAmount(value);
  props.update(value);
}

【讨论】:

  • 它不起作用我试过了。但是谢谢
  • 不可能,你做错了什么
  • 更新功能有效,但 setAmount 无效
  • 如果您喜欢我的回答或者您从我的回答中得到了任何帮助,请不要忘记考虑投票并通过单击右箭头将此答案作为您的最佳答案,谢谢!
猜你喜欢
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 2019-12-27
  • 2020-09-07
  • 1970-01-01
  • 2020-02-06
  • 2019-03-21
  • 2020-06-13
相关资源
最近更新 更多