为什么在useState中使用const声明状态变量?

时间:2019-12-18 19:13:28

标签: javascript reactjs react-hooks

在React 16的useState()钩子官方文档中,count状态及其设置函数声明为:

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

在提供的example中。

我的疑问是,为什么他们使用 const 作为状态变量,其值可以更改?

3 个答案:

答案 0 :(得分:1)

在React中,您不会直接更改状态变量。

在Class组件中,您永远不会Sub Prueba(): 'Define all variables Dim i As Double Dim rg As Range Dim strDataRange As Range Dim keyRange_d As Range Dim keyRange_z As Range i = 2 'Define last row count last_row = Cells(Rows.Count, 1).End(xlUp).Row 'Insert columns and divide date and hour 'Range("I:I").Insert Set rg = Range("H1").CurrentRegion rg.TextToColumns Destination:=Range("H1"), DataType:=xlDelimited, Space:=True End Sub ,而使用this.state.property = 'new value'来提供新的引用。

与钩子相同。您不必像this.setState({property: 'new value'})那样直接更改状态值,而必须使用count = 2来让React知道状态已更改(React也可以批量更新状态)。

如果您想进行更深入的研究,请查看official Reconciliation documentation,了解为什么React这样工作。 (提示:优化)。

答案 1 :(得分:0)

使用

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

您拥有状态变量的副本,即使您调用setCount

,副本也不会更改

答案 2 :(得分:-1)

这实际上不是关于React的,而是Flux。磁通量是涉及不可变状态存储的范式,对状态进行操作以将状态转换为不可变状态的新实例。