使用 React 基于类的组件,组件的状态值可以从类方法的 setInterval 中读取,因为组件中其他地方的逻辑会更改状态:
...
constructor(props) {
super(props);
this.state = {
someChangingStateValue: 'initial value'
}
}
...
// Elsewhere, at random:
this.setState({someChangingStateValue: 'suddenly changed'})
...
_handleLoop() {
setInterval(() => {
console.log(this.state.someChangingStateValue)
console.log("The above line prints the current state value correctly.")
}, 500)
}
...
但是,此模式不能与基于钩子的函数式 React 组件一起使用:
...
[someChangingStateValue, setSomeChangingStateValue] = useState('initial value')
...
// Elsewhere, at random:
setSomeChangingStateValue('suddenly changed')
...
const _handleLoop () => {
setInterval(() => {
console.log(someChangingStateValue)
console.log("The above line would always print 'initial value'.")
}, 500)
}
...
使用这些功能组件实现此目的的最佳方法是什么?
目前最干净的解决方案似乎是使用useRef()
创建一个引用:
import React, { useState, useRef } from "react";
...
[someChangingStateValue, setSomeChangingStateValue] = useState('initial value')
const someChangingStateValueRef = useRef();
someChangingStateValueRef.current = someChangingStateValue;
...
// Elsewhere, at random:
setSomeChangingStateValue('suddenly changed')
...
const _handleLoop () => {
setInterval(() => {
console.log(someChangingStateValueRef.current)
console.log("The above line prints the current state value correctly.")
}, 500)
}
...