[英]Updating component's state using props with functional components
我正在尝试使用从父组件获得的道具更新我的组件的 state,但我收到以下错误消息:
太多的重新渲染。 React 限制了渲染的数量以防止无限循环。
如果道具发生变化,我希望本地 state 更新。 类似的帖子( 使用道具更新组件的 state ,使用React 子组件上的道具更新 state , 使用道具更新组件的 Z9ED39E2EA931586B6A985A6942EF573E没有修复它)。
import React, {useState} from "react"
const HomeWorld = (props) => {
const [planetData, setPlanetData] = useState([]);
if(props.Selected === true){
setPlanetData(props.Planet)
console.log(planetData)
}
return(
<h1>hi i am your starship, type: {planetData}</h1>
)
}
export default HomeWorld
您只需要使用useEffect
挂钩来运行它一次。
import { useEffect } from 'react'
...
const HomeWorld = (props) => {
const [planetData, setPlanetData] = useState([]);
useEffect(() => {
if(props.Selected === true){
setPlanetData(props.Planet)
console.log(planetData)
}
}, [props.Selected, props.Planet, setPlanetData]) // This will only run when one of those variables change
return(
<h1>hi i am your starship, type: {planetData}</h1>
)
}
请注意,如果props.Selected
或props.Planet
发生变化,它会重新运行效果。
太多的重新渲染。 React 限制了渲染的数量以防止无限循环。
这里发生的是,当您的组件渲染时,它运行 function 中的所有内容,调用setPlanetData
将重新渲染组件,再次调用 function 中的所有内容(再次setPlanetData
)并进行无限循环。
你通常最好不要用道具更新你的 state 。 它通常使组件难以推理,并且通常会导致意外状态和陈旧数据。 相反,我会考虑类似的事情:
const HomeWorld = (props) => {
const planetData = props.Selected
? props.Planet
//... what to display when its not selected, perhaps:
: props.PreviousPlanet
return(
<h1>hi i am your starship, type: {planetData}</h1>
)
}
这可能需要在父组件中添加更多逻辑,以控制 Selected 属性为 false 时显示的内容,但它更符合 React 的习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.