【发布时间】:2020-10-11 07:05:44
【问题描述】:
我正在使用useSWR 从服务器获取更新。
const {data, error} = useSWR('url', url => fetch(url).then(r => r.json()), { refreshInterval: 1000 })
服务器返回:
{
"values": {
"width": 1920,
"height": 1080
}
}
然后我使用useEffect 像这样更新本地状态:
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
useEffect(() => {
if(data) {
setWidth(data.values.width)
setHeight(data.values.height)
// console.log statement to check whether this runs
console.log(`width: ${width}, height: ${height}`)
}
}, [data])
我的返回值为:
<div style={{ width, height }}></div>
状态已更新,我得到的日志表明width 和height 已从0、0 更新为1920、1080。但是组件的宽度和高度保持0px,0px。
知道为什么会这样吗?
更新
这与反应无关。 我的服务器返回的是字符串值而不是整数。控制台日志正在打印不带引号的字符串,所以我错过了它。 在开发人员工具中查看组件的尺寸显示 NaNpx,NaNpx。 修复服务器端返回值,修复问题。
【问题讨论】: