import React from "react"
import ReactDOM from "react-dom"
import "./styles.css"
function usePersistentValue(initialValue) {
return React.useState({
current: initialValue
})[0]
}
function Counter() {
const [count, setCount] = React.useState(0)
const id = usePersistentValue(null)
const clearInterval = () => window.clearInterval(id.current)
React.useEffect(() => {
id.current = window.setInterval(() => {
setCount(c => c + 1)
}, 1000)
return clearInterval
}, [])
return (
<div>
<h1>{count}</h1>
<button onClick={clearInterval}>Stop</button>
</div>
)
}
const rootElement = document.getElementById("root")
ReactDOM.render(<Counter />, rootElement)
这里
function usePersistentValue(initialValue) {
return React.useState({
current: initialValue
})[0]
}
这似乎是一个函数调用,但后跟 [0] 对我来说毫无意义,尤其是 [0] 在这里做什么?它是有效的javascript还是反应的特殊语法?我最好的猜测是 [0] 值被分配给current
属性,对吗?但我仍然困惑如何将数组值分配给current
属性,请帮我解释语法谢谢