簡體   English   中英

每次在 React Native 中渲染組件之前獲取數據和 setState

[英]Fetch data and setState every time just before component renders in React Native

在這種情況下,我有一個模態,它顯示了來自其 state (一個數組)的一些數據,它的 state 正在像 docsC14A 建議的那樣在 componentDidMount() ZC1C425268E68385D1AB5074C17 中設置。 每次打開模式時我都需要顯示更新的數據。所以我可以使用 componentWillReceiveProps(nextProps) function 來做到這一點,如下所示。
但是如果我想遷移到 getDerivedStateFromProps function 怎么辦? 我將如何實現與它相同的行為?

下面是簡化的組件代碼:

export class PastOrdersModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      past: {},
      isLoading: false,
      modalVisible: false
    };
  }

  async componentWillReceiveProps(nextProps) {  
    const response = await this.fetchPast();
    this.setState({ past: response });
  }

  async componentDidMount() {
    const response = await this.fetchPast();
    this.setState({ past: response });
  }
   ...
   ... some callback functions for handling modalvisible value ....
   ...
   render(){
   // here rendering state array with this.state.past.map(......) etc.
  }

fetchPast function 向我的服務器發出 GET 請求,您只需要知道它返回一個數組給我。 這是完美的工作。 ComponentWillReceiveProps 每次都會被調用,因為父組件每次都會發送 modalVisible 道具。
但是 componentWillRecieveProps 已棄用,我無法使用 getDerivedStateFromProps 做出相同的行為。我應該如何用它實現相同的功能。

注意:我不會使用 redux,我不會使用 mobx,我知道如何使用它們,這不是我想要的。 問題是我想要的行為太簡單了我不想將值傳遞給另一個組件,我不想將值傳遞給另一個屏幕,我只想更新一個簡單的組件,除了框架正在推動它限制使最簡單的任務變得最困難,或者我錯過了非常重要的一點。(可能是后一個:))

注意:我知道我沒有對 nextProps 做任何事情,這是我找到的唯一解決方案。

您可以將組件編寫為 function 以便您可以使用React Hooks

const PastOrdersModal = (props) => {
  const [past, setPast] = useState({});
  const [isLoading, setLoading] = useState(false);
  const [modalVisible, setModalVisibility] = useState(false);

  useEffect(() => {
    const fetchPast = async () => {
      const response = await fetchPast();
      setPast(response);
    };
    if(modalVisible) fetchPast();
  }, [modalVisible])

  useEffect(() => {
    const fetchPast = async () => {
      const response = await fetchPast();
      setPast(response);
    };
    fetchPast();
  }, [])

   ...
   ... some callback functions for handling modalvisible value ....
   ...
   return <YourComponent />

我們在頂部[]中創建的變量是我們用於 state 的變量。 第一個將是 state 本身,第二個是負責更新 state 的 function。 useEffect掛鈎將模擬 Class 組件的生命周期方法,它接收將執行的回調和第二個參數。 第二個參數將指示何時觸發。 例如,您可以看到 2 個useEffect ,帶有空數組的那個將告訴鈎子只執行一次,類似於componentDidMount 另一個將在modalVisible更改時觸發,因此每次更改其值時都會執行,這就是為什么我們僅驗證模態是否可見(為true )我們進行獲取,否則將不會執行獲取

暫無
暫無

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

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