【问题标题】:"variable" is read only“变量”是只读的
【发布时间】:2020-06-15 02:54:52
【问题描述】:

我有以下代码,但出现“计数”错误是只读的:

import React, {useState} from 'react';
import {View, Text, StyleSheet, Button} from 'react-native';

const CounterScreen = () => {
  const [count, setCount] = useState(0);

  return (
    <View>
      <Button onPress={() => setCount(count++)} title="Increase" />
      <Button onPress={() => setCount(count--)} title="Decrease" />
      <Text>Current Counter: {count}</Text>
    </View>
  );
};

const styles = StyleSheet.create({});
export default CounterScreen;

但如果我使用setCount(count + 1) 而不是setCount(count++),它会完美运行。这里count + 1count++有什么区别

【问题讨论】:

    标签: javascript reactjs react-native react-hooks


    【解决方案1】:

    要记住的重要一点是,您可以更改声明为 const 的变量的值,但不能重新分配它。这是一篇很好的博客文章:

    https://mathiasbynens.be/notes/es6-const

    setCount(count+1) 获取变量 count 的当前值,将其加 1,然后将其传递给我们的 setter 函数 'setCount' 以更新我们的状态。我们绝不会重新分配“count”变量。 React 正在使用 setter 函数在后台更新 'count' 的值。

    您对 count++ 所做的是尝试重新分配 count 变量,而不仅仅是更改“count”变量的值。

    【讨论】:

      【解决方案2】:

      count++ 是count = count + 1; 的简写,您实际上是在更改变量的值。不仅仅是读取它的价值。

      【讨论】:

        【解决方案3】:

        count++ 类似于count = count + 1 意味着它正在改变变量本身 而且您知道const 在初始化后是只读的,这就是您执行setCount() 来更新值的原因。

        count + 1 没有自我更新。

        【讨论】:

          【解决方案4】:
          const [count, setCount] = useState(0);
          

          你在 ↑ 的计数是read only,如果你想改变它的值必须打电话给setCount()

          点赞setCount(num)

          所以如果num= 10 则等于setCount(10)

          所以setCount(count + 1) 可以工作,count+1 是一个数字

          但是为什么setCount(count++)不能工作是因为

          count++
          

          等于

          count=count+1; //It is changing the value of count directly!
          
          setCount(count++) 
          
          setCount(count=count+1) //So count++ is changing the value of count directly, not through setCount, couldn't work.
          

          它无法工作,并且可能会为"count" is read-only 出错

          这是尝试更改计数值而不在setCount 中调用setCount

          【讨论】:

            猜你喜欢
            • 2015-08-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-01-23
            • 2015-01-31
            • 2015-11-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多