【问题标题】:React Native I am having issues with adding a number from stateReact Native 我在从状态中添加数字时遇到问题
【发布时间】:2022-01-07 09:36:52
【问题描述】:

react native 不会将我的数字增加 2,而是将新文本添加到我的状态。减去问题只是添加时我没有问题

const [vol, setVol] = useState(10)

useEffect(()=>{
  setVol(e=> e + 2)
},[])

console.log(vol)
// output 102

我需要将状态 vol (10) 增加 2,所以输出应该是 12

【问题讨论】:

  • 您确定没有在任何地方将您的状态值设置为字符串吗?
  • @NickParsons 刚刚发现数字已从 ayncStorage 转换为字符串

标签: javascript react-native


【解决方案1】:

e 将是一个字符串,因此将在添加字符串之前将其更改为 Number const [vol, setVol] = useState(10)

useEffect(()=>{
  setVol(e=> String(Number(e) + 2))
},[])

console.log(vol)
// output 12

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2020-09-02
    • 2023-04-03
    • 2021-11-20
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多