繁体   English   中英

功能组件不会在道具更改时重新渲染

[英]functional component doesn't re-render on props change

在下面的代码中,每当我从父级获得新道具时,新道具都会正确记录在控制台上,但渲染的 HTML 在初始渲染后永远不会更新:

export default function(props) {
  const [state, setState] = useState(props)
  
  // initially, props.something is defined
  // every time props changes (from the parent) props.something is redefined as expected and logged here
  console.log(props.something)
  
  // initially, props.something is rendered correctly
  // every time props.something changes (from the parent) the HTML never updates
  return (
    {state.something && <div>{state.something}</div>}
  )
} 

我已经尝试使用useEffect() ,尽管我看不出有什么意义,但它并没有解决任何问题。

State 不会因为 props 改变而更新,这就是你需要useEffect的原因。

export default function(props) {
  const [state, setState] = useState(props)

  useEffect(() => {
    setState(props.something)
  }, [props.something])
  
  // initially, props.something is defined
  // every time props changes (from the parent) props.something is redefined as expected and logged here
  console.log(props.something)
  
  // initially, props.something is rendered correctly
  // every time props.something changes (from the parent) the HTML never updates
  return (<div>{state.something}</div>)
} 

props.something添加到数组中作为useEffect的第二个参数,告诉它监视props.something的变化并在检测到变化时运行效果。

在您的示例中,您仅在设置初始值时将道具复制到 state 一次。

不过,将道具复制到组件 state 几乎不是一个好主意。 你可以阅读它的反应文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM