【问题标题】:Updating component's state using props with functional components使用带有功能组件的道具更新组件的状态
【发布时间】:2020-01-24 15:57:56
【问题描述】:

我正在尝试使用从父组件获取的道具更新组件的状态,但我收到以下错误消息:

重新渲染过多。 React 限制渲染次数以防止无限循环。

如果道具发生变化,我希望更新本地状态。 类似的帖子(Updating component's state using propsUpdating state with props on React child componentUpdating component's state using props)并没有为我修复它。

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

【问题讨论】:

  • 您为什么要尝试使用道具更新状态?为什么不只渲染props.Planet 而不是planetData
  • @Retsam 我会问同样的问题,但正如您在他提到的其他问题中看到的那样,我认为他真的很想拥有该州的道具。
  • 我对 Retsam 也有同样的想法。

标签: javascript reactjs react-hooks


【解决方案1】:

您只需要使用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.Selectedprops.Planet发生变化,会重新运行效果。

为什么会出现此错误?

重新渲染过多。 React 限制渲染次数以防止无限循环。

这里发生的是,当你的组件渲染时,它会运行函数中的所有内容,调用 setPlanetData 它将重新渲染组件,再次调用函数内的所有内容(再次调用setPlanetData)并进行无限循环。

【讨论】:

    【解决方案2】:

    您通常最好不要使用道具更新您的状态。它通常使组件难以推理,并且通常会导致意外状态和陈旧数据。相反,我会考虑这样的事情:

    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 的习惯。

    【讨论】:

      猜你喜欢
      • 2017-05-11
      • 2021-01-28
      • 2023-01-17
      • 2020-05-15
      • 2020-04-30
      • 2021-07-21
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多