【问题标题】:React Native: You attempted to set the key on an object that is meant to be immutable and has been frozenReact Native:您试图在一个本应是不可变且已被冻结的对象上设置键
【发布时间】:2019-01-20 02:02:49
【问题描述】:

我是原生反应的新手,并且正在创建我的第一个。

在我的添加中,我决定动态更改我的应用程序的背景颜色,为此我做了类似的事情

let style = StyleSheet.flatten({
    upperRow: {
        display: "flex",
        flexDirection: "row",
        marginBottom: 5, 
        backgroundColor: "white"
    },
})

let {
    upperRow
} = style 

然后在componentWillReceiveProps中出现类似的内容

componentWillReceiveProps(nextProps) {

    if (this.props.coinPrice != nextProps.coinPrice ) {
       if (this.props.coinPrice > nextProps.coinPrice) {
        console.log("previous value is greater")
           //change background color to red
           upperRow["backgroundColor"] = "#ffe5e5"
           console.log(upperRow)
           //We 
       }
     }
    }

这是抛出以下错误

您尝试将键 backgroundColor 设置为值 #ffe5e5 在一个本来是不可变的对象上 冷冻。

问题:谁能告诉我这里出了什么问题?

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    关于Stylesheet你应该知道的一些事情:

    • 当您执行Stylesheet.flatten 时,它会将样式对象数组展平为一个不可变样式对象。
    • 当你做Stylesheet.create时,它会生成一个不可变的样式对象。

    但为什么它必须是不可变的?

    参考documentation,为了提高性能,样式对象的不变性将使UI和JS Thread之间的通信更简单。换句话说,它们将只使用样式对象的 ID 通过本机桥相互通信。所以,对象不能被改变。

    这个问题的解决方法就这么简单:

    • 使用样式数组。
    • 使用状态动态更新样式。

    下面是演示如何做到这一点的代码:

    class App extends React.Component {
    
      state = {
        clicked: false
      }
    
      handleOnPress = () => {
        this.setState(prevState => ({clicked: !prevState.clicked}))
      }
    
      render() {
        return (
          <View style={[styles.container, {backgroundColor: this.state.clicked ? "blue" : "red"}]}>
            <Button onPress={this.handleOnPress} title="click me" />
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
      },
    });

    这里是代码的Snack Expo链接:https://snack.expo.io/SJBLS-1I7

    【讨论】:

    • 这是一个很好的答案和信息,我真的只能在这里找到。所以感谢提供。如果可以的话,我会给你更多的支持!
    猜你喜欢
    • 2016-11-11
    • 2021-05-29
    • 2019-12-28
    • 2018-02-13
    • 2017-02-26
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    相关资源
    最近更新 更多