在下面的代码中,每当我从父级获得新的 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/