簡體   English   中英

“prevState”和“prevProps”在 React Native 中的行為不符合預期

[英]"prevState" and "prevProps" not behaving as expected in React Native

我的 React Native 項目中有一個處於我狀態的數組,如下所示:

constructor(props) {
  super(props)
  this.state = {
    a: [1, 2, 3]
  }
}

我單擊一個按鈕來更新數組,如下所示:

<TouchableOpacity
  onPress={() => {this.setState({a: [5, 6]})}
/>

我想驗證我的componentDidUpdate()方法中的狀態更改,如下所示:

componentDidUpdate(prevProps, prevState) {
  console.log("prevState: ", prevState)
  console.log("state: ", this.state)
}

但這總是給

prevState:  (5) [-1, -1, -1, -1, -1]
state:  (5) [-1, -1, -1, -1, -1]

我使用 devTools 確認數組確實更新到 [5, 6],但是componentDidUpdate()方法仍然只是返回舊值。 知道為什么嗎?

謝謝!

componentDidUpdate()應始終包含在條件中,以便您需要添加setState()方法。

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

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

您可以在 componentDidUpdate() 中立即調用 setState() 但請注意,它必須包含在類似於上面示例中的條件中,否則會導致無限循環。 它還會導致額外的重新渲染,雖然對用戶不可見,但會影響組件性能

另請檢查此答案以供參考: 在 ReactJS 中正確修改狀態數組

我確實實現了你的代碼,我的正在工作。

這是我的代碼:

import React, { Component } from "react";
import { View, Text, Button, SafeAreaView } from "react-native";

import { baseStyles as styles  } from "../styles";

export default class Fetch extends Component{
  constructor(props) {
    super(props)
    this.state = {
      a:[1, 2, 3]
    }
  }

  componentDidUpdate(prevProps, prevState) {
    console.log("prevState: ", prevState)
    console.log("state: ", this.state)
    alert(this.state.a)
  }

  render(){
    return(
    <SafeAreaView>

        <View style={styles.container}>
        <Text>
            Main Dish
        </Text>
        <Button
        title='press'
  onPress={() => {this.setState({a: [5, 6]})}}
/>
        </View>


    </SafeAreaView>

    )
  }
}
  1. 確保您將兩個數組與:
componentDidUpdate(prevProps){
  if(JSON.stringify(prevProps.todos) !== JSON.stringify(this.props.todos){...}
}
  1. 確保在深度克隆后更改傳遞的道具(父級中的狀態):
let newtodos = JSON.parse(JSON.stringify(this.state.todos));
newtodos[0].text = 'changed text';
this.setState({ todos : newtodos });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM