为什么setStateval中的setState不能使用带有react-native的useEffect进行更新? [重复]

问题描述 投票:0回答:1

我的组件是:

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

javascript reactjs react-native react-hooks use-effect
1个回答
3
投票

从react文档:

将setState()视为请求而不是立即命令更新组件。为了获得更好的感知性能,React可能会延迟它,然后一次通过更新几个组件。反应不保证状态更改会立即应用。

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

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

上面的链接中有更多信息。希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.