为什么我的 setState 不会使用带有 react-native 的 useEffect 在 setInterval 中更新?

Why won't my setState update in a setInterval using a useEffect with react-native?

我的组件是:

export default function TopHalf(props) {
    const [startDegrees, setStartDegrees] = useState(0)

    useEffect(() => {
        const centerPoint = { x: dim.width / 2, y: dim.height / 4 }
        setCenter(centerPoint)

        setInterval(() => {
            console.log('startDegrees', startDegrees)
            setStartDegrees(startDegrees + 5)
        }, 500)
    }, [])
...
    return (
        <HalfView style={{ top: 0, position: 'absolute', width: '100%' }} >
            {props.participants?.map(circularParticipants)}
        </HalfView>
    )
}

所以你可以看到 startDegrees 应该每半秒增加 5。但是当我注销时它停留在0

来自反应文档:

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

https://reactjs.org/docs/react-component.html#setstate

在这种情况下,react 可能没有更新状态,所以日志正在读取原始值。为避免 setState 的并发问题,您可以将回调作为第二个参数传递,在执行 setState 时调用该回调。这样它总是会在更新之前直接获取值。

上面的 link 中有更多信息。希望这对您有所帮助!