【问题标题】:SOLVED: useState updates but component does not re-render已解决:useState 更新但组件不会重新渲染
【发布时间】: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>

状态已更新,我得到的日志表明widthheight 已从00 更新为19201080。但是组件的宽度和高度保持0px0px

知道为什么会这样吗?

更新

这与反应无关。 我的服务器返回的是字符串值而不是整数。控制台日志正在打印不带引号的字符串,所以我错过了它。 在开发人员工具中查看组件的尺寸显示 NaNpx,NaNpx。 修复服务器端返回值,修复问题。

【问题讨论】:

    标签: reactjs next.js use-state


    【解决方案1】:

    异步响应更新状态,因此在触发 setState 后添加 console.log 并不意味着状态已更新。检查宽度和高度的变化使用useEffect这样的钩子:

    useEffect(()=>console.log(height,width),[width,height])
    

    每次高度或宽度改变时都会触发此效果。

    【讨论】:

    • 感谢您的指出。但是使用效果很好。经过进一步调查,我发现服务器将宽度和高度作为字符串返回。由于样式对象仅接受 px 值作为整数,因此我的组件使用 NaNpx、NaNpx 尺寸呈现。在将值设置为 useState 之前将其转换为数字可解决此问题。显然我还是新手。
    【解决方案2】:

    试试这个

     <div style={{ width :`${width}px` ,height: `${height}px` }}></div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 2020-02-13
      相关资源
      最近更新 更多