【问题标题】:react native "attempt to set value to an immutable object"反应原生“尝试为不可变对象设置值”
【发布时间】:2017-06-21 20:04:05
【问题描述】:

我正在创建一个可拖动的框。我可以将其拖动到屏幕上的任何位置,但我收到此错误消息,提示“您试图在一个本应不可变且已被冻结的对象上设置密钥 _value”。谁能告诉我我做错了什么。

我的代码:

import React, { Component } from 'react'
import {
  AppRegistry,
  StyleSheet,
  Text,
  Button,
  ScrollView,
  Dimensions,
  PanResponder,
  Animated,
  View
} from 'react-native'

import { StackNavigator } from 'react-navigation'




export default class Home extends Component{

componentWillMount(){

  this.animatedValue = new Animated.ValueXY();

this.panResponder = PanResponder.create({

 onStartShouldSetPanResponder: (evt, gestureState) => true,
  onMoveShouldSetPanResponder: (evt, gestureState) => true,
  onPanResponderGrant: (e, gestureState) => {



      },

  onPanResponderMove:Animated.event([


null,{dx: this.animatedValue.x , dy:this.animatedValue.y}

    ]),  
  onPanResponderRelease: (e, gestureState) => { 
      },       
})
}

  render(){

    const animatedStyle = {

      transform:this.animatedValue.getTranslateTransform()
    }

    return(

        <View style={styles.container}>

        <Animated.View style={[styles.box ,animatedStyle]} {...this.panResponder.panHandlers}>


        <Text>Home</Text>


        </Animated.View>
        </View>
      )
  }
}


var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginLeft: 10,
    marginRight: 10,
    alignItems: 'stretch',
    justifyContent: 'center',
  },

  box:{

height:90,
width:90,
textAlign:'center'



  }
});

【问题讨论】:

  • 有行号吗?我的猜测是它与const animatedStyle 有关,因为“不可变”意味着“无法更改”。 this.animatedValue.getTranslateTransform() 可能不是恒定的。我不是 100% 确定,但是将 const 更改为 var 可能会解决问题,但我不确定你为什么将其设置为 const 开头,所以也许我错了。 LMK 如果有效,如果有效,我会将其添加为答案而不是评论。
  • 感谢您期待我的问题先生,我尝试了但仍然出现同样的错误。 :(
  • 不确定这是否是问题所在,但您在 animatedStyle 中拼错了“transform”
  • 感谢您指出@Matt Aft。我在堆栈上输入错误,虽然它在我的代码中是正确的。
  • @MattAft 哇,实际上我的代码中的 transform 拼写错误。谢谢!哈哈

标签: javascript android reactjs react-native react-animated


【解决方案1】:

就我而言,我收到此错误是因为我忘记将 View 更改为 Animated.View

【讨论】:

    【解决方案2】:

    试试这个。这将解决您的问题。 您需要在 state 对象中初始化 animatedValue 以使其工作。

    constructor(props) {
      super(props);
      this.state = {
        animatedValue: new Animated.ValueXY()
      }
    }
    
    onPanResponderMove:Animated.event([
     null,{dx: this.state.animatedValue.x , dy:this.state.animatedValue.y}
    ]),
    

    【讨论】:

    • 我的动画值处于状态,但我得到了同样的错误。
    猜你喜欢
    • 2020-02-27
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2019-04-17
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多