reactjs - 功能组件不会在 Prop 更改时重新渲染

标签 reactjs

在下面的代码中,每当我从父级获得新的 Prop 时,新的 Prop 都会正确地记录在控制台上,但渲染的 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 的变化并运行检测到变化时的效果。

更新:在这个具体的例子中,没有理由将props复制到state,直接使用prop即可。

关于reactjs - 功能组件不会在 Prop 更改时重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72369801/

相关文章:

javascript - React - 尽管有默认值,但复选框值未定义

javascript - 如何修复我的 ReactJS Redux 应用程序中的 "Error: Reducers may not dispatch actions."?

reactjs - 我如何使用 fs 与 Electron react ?

javascript - 如何在 React 应用程序中访问 this.refs 不可用的函数中的 DOM 元素?

javascript - 扩展深层嵌套 prop 中的属性 ImmutableJS

mysql - Cpanel 上的 Express/NodeJS 应用程序

reactjs - reduxForm 中的 'pristine' 和 'submitting' 是什么?

javascript - webpack 无法解析 node_modules Material 图标

javascript - 如何存储获取的数据

arrays - react 原生 : Key Value array or hasmap?