亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 componentDidUpdare 中 React setState 導致超出最大更新深度

在 componentDidUpdare 中 React setState 導致超出最大更新深度

慕仙森 2023-11-02 21:57:11
我正進入(狀態錯誤:超出最大更新深度。當組件在 componentWillUpdate 或 componentDidUpdate 中重復調用 setState 時,可能會發生這種情況。React 限制嵌套更新的數量以防止無限循環。但我讀到的內容應該能夠在 componentDidMount 中調用 setState 而不會出現錯誤。class MyComponent extends Component {constructor(props) {    super(props);    this.state = {        matchtedProducts: [],        products: [],    }}async componentDidMount() {    try {        const products = await getProducts()        this.setState({ products })    } catch(err) {        console.log(err)    }}componentDidUpdate() {    const productColor = this.props.size.trim().toLowerCase()    const productSize = this.props.color.trim().toLowerCase()    const matches = []    this.state.products.map(product => {        const title = product.title        const titleSpliitet = title.split(',')        let color = titleSpliitet[1].trim().toLowerCase()        let size = titleSpliitet[2].trim().toLowerCase()        if(color == productColor && size == productSize) {            matches.push(product)        }    })    this.setState({matchtedProducts: matches})}render() {    return (<div></div>)}}
查看完整描述

4 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

發生這種情況是因為每個 setState 都會觸發一次渲染,然后再次觸發一次 componentDidMount,這基本上會導致無限循環。要停止該循環,您需要設置一些條件,以防止再次渲染,例如


    componentDidUpdate(previousProps, previousState) {

    if (previousProps.data !== this.props.data) {

        this.setState({/*....*/})

    }

   }


查看完整回答
反對 回復 2023-11-02
?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

我遇到了同樣的錯誤。在使用效果方法中,我使用 axios 從后端獲取數據并更新了狀態。但在更新狀態之前,我沒有將 json 數據轉換為狀態的數據類型,這就是導致此錯誤的原因。


錯誤代碼 :


Useeffect(() => {

    fetch

       .then((res) =>{

           setDate(res.data.date)

       }) 

})

正確代碼:


Useeffect(() => {

    fetch

        .then((res) =>{

            setDate(new Date(res.data.date)) 

    }) 

}) 


查看完整回答
反對 回復 2023-11-02
?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

看來你想在 props 改變時改變狀態來過濾一些產品。我刪除componentDidUpdate代碼并在組件中添加一個方法來進行過濾,然后我將從父組件中調用該方法


class MyComponent extends Component {

constructor(props) {

    super(props);

    this.state = {

        matchtedProducts: [],

        products: [],

    }

}

async componentDidMount() {

    try {

        const products = await getProducts()

        this.setState({ products })

    } catch(err) {

        console.log(err)

    }

}


updateMatches = () => {


    const productColor = this.props.size.trim().toLowerCase()

    const productSize = this.props.color.trim().toLowerCase()

    const matches = []


    this.state.products.map(product => {

        const title = product.title

        const titleSpliitet = title.split(',')


        let color = titleSpliitet[1].trim().toLowerCase()

        let size = titleSpliitet[2].trim().toLowerCase()


        if(color == productColor && size == productSize) {

            matches.push(product)

        }


    })

    this.setState({matchtedProducts: matches})


}


render() {

    return (<div></div>)

}


}

并在父組件中


changeSizeAndColor = () => {

     //note that I called updateMatches of MyComponent  

     this.setState({color : ... , size : ...} , () => this.myComponent.updateMatches());

}


render() { 

    return <MyComponent ref={ref => this.myComponent = ref} color={...} size={...}/>

}


查看完整回答
反對 回復 2023-11-02
?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

我認為你必須傳遞prevProps和/或prevState作為 的參數componentDidUpdate,并且僅當狀態的 prop 或屬性發生更改時才執行代碼,


例子:


componentDidUpdate(prevProps, prevState) {

  // if the property count of the state has changed

  if (prevState.count !== this.state.count) {

    // then do your code

  }

}

文檔:https ://en.reactjs.org/docs/react-component.html#componentdidupdate


查看完整回答
反對 回復 2023-11-02
  • 4 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號