在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的新手,如果有同样的方法的话,请随意写作。
const [exchangeRatio, setExchangeRatio] = useState();
const [toCurValue, setToCurValue] = useState();
上面的语句表示您正在用分别存储在exchangeRatio
和toCurValue
中的值声明一个状态,并且这些状态只能分别使用setExchangeRatio
和setToCurValue
方法进行修改。
使用useState()
声明状态时,需要将useState()
中状态的初始值指定为参数。例如,如果您希望exchangeRatio
的初始值为10,则必须将其写成-
const [exchangeRatio, setExchangeRatio] = useState(10);
现在,由于您还没有提供初始状态值,因此控制台记录的输出是未定义的。一旦用正确的值正确初始化它,就可以直接使用状态,存储的值就会返回给您。
因此,假设您想将toCurValue
的值设置为等于exchangeRatio
的值(已正确初始化(,那么您可以在编写useState((时执行此操作,也可以通过以下方式使用setToCurValue
-
const [toCurValue, setToCurValue] = useState(exchangeRatio);
或
setToCurValue(exchangeRatio);