【问题标题】:Get a number value from an object in React state从处于 React 状态的对象中获取数值
【发布时间】:2018-03-19 08:07:03
【问题描述】:

我在处理处于 react-native 组件状态的数据时遇到了一个奇怪的问题。

我先定义状态:

    this.state = {
        bonesPosition: {
            black: [{x: 0, y: 0}, {x: 0, y: 0}, {x: 0, y: 0}],
            white: [{x: 0, y: 0}, {x: 0, y: 0}, {x: 0, y: 0}]
        }
    };

然后我更新它:

const bonesPosition = {...this.state.bonesPosition};

bonesPosition.white[0].x = this.firstWhite.state.pan.x;

this.setState({bonesPosition})

但是当我尝试访问数据时,

const whiteX = this.state.bonesPosition.white[index].x;

console.log(whiteX)
console.log(typeof whiteX)
console.log(parseInt(whiteX))
console.log(Number(whiteX))

它向我显示了值,但我可以用它计算,因为它是一个对象。但是如果我尝试将其转换为数字,它就不再识别数字值了。

44.5
object
NaN
NaN

有什么想法吗?

【问题讨论】:

  • 因为它已经是一个数字了?
  • whiteXobject,而不是 numberstring。所以,parseInt 很可能会失败。 whiteX 可能是覆盖了 toStringvalueOf 方法的对象。您需要深入研究实现以找出确切的问题。
  • 为什么数字或字符串不是对象?
  • 什么是this.firstWhite.state.pan.x
  • 能不能设置一个调试器,看看whiteX的原型是什么?

标签: javascript reactjs object react-native


【解决方案1】:

难道你有一个 Animated.Value 而不是一个简单的数字?

pan 和 bonePosition 推断,这看起来像 panResponder 的代码

https://facebook.github.io/react-native/docs/animations.html#tracking-gestures

您应该检查返回的值/对象类型并通读动画文档。

希望对你有帮助

【讨论】:

  • 好的,谢谢!我不得不将this.firstWhite.state.pan.x 更改为this.firstWhite.state._value.x
猜你喜欢
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 2020-03-08
  • 1970-01-01
相关资源
最近更新 更多