“变量”是只读的

时间:2020-06-15 02:54:52

标签: javascript reactjs react-native react-hooks

我有以下代码,并且我收到“计数”错误为只读的信息:

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++

有什么区别

4 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

count ++与count = count + 1类似 表示它正在更改变量本身 并且您知道const在初始化后是只读的,这就是为什么您进行setCount()来更新值。

count + 1不会自我更新。

答案 3 :(得分:0)

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