簡體   English   中英

react-native:狀態未在componentWillReciveProps內部更新

[英]react-native : state not updated inside the componentWillReciveProps

我正在尋找很多方法來解決這個問題,但是沒有人可以使用, setState仍然無法在componentWillReciveProps方法內部工作,這是我的代碼:

export class Detail extends React.Component
{
  constructor(props)
  {
    super(props);
    this.state = {
      ids: 'ger'
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ ids: nextProps.data }, () => {
          console.log(nextProps.data+"=this id")
      });
  }


  render()
   {
    return (
      <View>
        <Text>{this.state.ids}</Text>
      </View>
    );
  }
}

如果我做console.log(nextProps.data+"=this id")它可以將我想要更新的id返回到this.state.ids 但是在渲染中的<Text>{this.state.ids}</Text>中仍顯示this.state.ids ('ger')的默認值,這意味着this.state.idscomponentWillReceiveProps未更新。

setState()並不總是立即更新組件。

您可以在這里找到所需的一切。

實際上作為反應文檔說:“在安裝過程中,React不會使用初始道具來調用componentWillReceiveProps。它僅在組件的某些道具可能更新時才調用此方法。調用this.setState通常不會觸發componentWillReceiveProps。”

您可以在這里找到更多。

在我看來,這是一種反模式。 為什么不將nextProps.data作為ID直接注入到Detail組件中? 然后,您可以像這樣直接輸出id:

<Text>{this.props.ids}</Text>

通常,您還應該得到一條警告,即在“ componentWillReceiveProps”中調用setState將無效。 如果您確實想更新狀態,則可以執行“ this.state.ids = nextProps.data”。

暫無
暫無

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

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