总的来说,这个 React 应用程序似乎按预期运行。 但是,当刷新页面时,只有部分更改的状态被保留并正确重新渲染,而另一部分则重置回默认状态。
如果我返回 VS code 并进行任何不相关的更改(例如添加注释),保存,然后返回浏览器,则默认状态将被更新并再次正确呈现。
所以看起来新状态的反射被延迟了1步,但我不确定到底是什么导致了这种奇怪的行为。
使用
react-query
v.5 获取数据
这是组件中的代码:
const tempU = [
{
id: 0,
name: 'metric',
symbol: 'C'
},
{
id: 1,
name: 'imperial',
symbol: 'F'
},
{
id: 2,
name: 'standard',
symbol: 'K'
},
]
const WeatherDisplay = () => {
const [currentPosition] = useAtom(currentPositionAtom)
const [, clearCoordinates] = useAtom(clearCoordinatesAtom)
const [tempUnitID, setTempUnitID] = useAtom(tempUnitIDAtom)
const selectedTempUnitName = tempU[tempUnitID] && tempU[tempUnitID].name
// This logs the state correctly everytime
console.log('selectedTempUnitName: ', selectedTempUnitName)
const { data: weatherData, refetch } = useGetCurrentWeather({
currentPosition,
selectedTempUnitName
})
return (
<div className={`${style['WeatherDisplay']}`}>
<h1 className={`${style['temperature']}`}>
<span onClick={setTemperatureUnitHandler}>
// This shows old state after a page reload: (State persisted, but delayed by 1 step)
{weatherData?.main && Math.round(weatherData?.main.temp)}
// This always shows up correctly
°{tempU[tempUnitID].symbol}
</span>
</h1>
</div>
);
};
export default WeatherDisplay;
这是浏览器上的样子:
页面刷新后立即。请注意,控制台会在第一个日志中记录默认状态,然后再记录最新状态。由于某种原因,来自 API 的状态不会立即重新渲染。
对代码进行不相关的更改(例如添加注释)并保存编辑器后,只有最新状态才能正确反映在浏览器中。 这种延迟是意外的,不应该发生。请注意控制台中的日志仍然显示正确的状态。
非常感谢任何帮助:))
问题终于解决了!!! :D!!
这个问题的解决方案是如此简单,我简直不敢相信!!!
该bug是因为
tempUnitID
中缺少初始值,导致状态按照分配的默认状态渲染!
在
SearchBar.tsx
中,我使用 useEffect()
检查 tempUnitID
是否已保存初始值。
如果最初没有保存
tempUnitID
值,则只需保存 setTempUnitID(0)
,以便 WeatherDisplay.tsx
可以检测到它并使用它来渲染正确的状态。
非常感谢您的阅读:D!!!
const [tempUnitID, setTempUnitID] = useAtom(tempUnitIDAtom)
useEffect(() => {
if (!tempUnitID) {
setTempUnitID(0)
}
}, [tempUnitID])