如何在 React 中提取状态值
How to extract value of a state in React
在我的 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);
在我的 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);