【问题标题】:How to extract value of a state in React如何在 React 中提取状态的值
【发布时间】:2020-11-08 06:23:30
【问题描述】:

在我的App.jsx 中使用多个状态变量时,我想将一个状态的值设置为与另一种状态的值相等。

const [exchangeRatio, setExchangeRatio] = useState();
const [toCurValue, setToCurValue] = useState();

function foo()
{
   setToCurValue(exchangeRatio);
}

console.log(exchangeRatio);

{exchangeRatio: undefined}
exchangeRatio: undefined
__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

继续

console.log({exchangeRatio}.valueOf());
>>Undefined

如果有办法做同样的事情,我是 React 的新手,请随意写。

【问题讨论】:

  • 如果第二个状态有第一个状态的值,那你为什么还需要两个状态?
  • 它们也可以不同,这只是我希望它们相同的一种特殊情况。

标签: reactjs react-hooks use-state react-state


【解决方案1】:
const [exchangeRatio, setExchangeRatio] = useState();
const [toCurValue, setToCurValue] = useState();

上述语句表示您正在声明一个状态,其值分别存储在exchangeRatiotoCurValue 中,并且只能分别使用setExchangeRatiosetToCurValue 方法修改这些状态​​。

当您使用useState() 声明状态时,您需要在useState() 中指定状态的初始值作为参数。例如。如果你想让exchangeRatio的初始值为10,那么你必须写成-

const [exchangeRatio, setExchangeRatio] = useState(10);

现在,由于您没有提供初始状态值,因此您将控制台记录的输出显示为未定义。一旦你用合适的值正确初始化它,你就可以直接使用状态,存储的值会返回给你。


所以,假设您想将toCurValue 的值设置为等于exchangeRatio 的值(已正确初始化),那么您可以在编写 useState() 或使用@987654332 时执行此操作@通过以下方式-

const [toCurValue, setToCurValue] = useState(exchangeRatio);

setToCurValue(exchangeRatio);

【讨论】:

  • 谢谢,它没有工作,因为我没有初始化状态。
猜你喜欢
  • 2016-04-24
  • 2021-10-28
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2021-10-28
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多