簡體   English   中英

ES6 類實例變量如何工作

[英]How does ES6 class instance variable work

我有以下代碼按預期工作:

import React, { Component } from 'react';

let result = null;
class MyData extends Component {
  _getData = () => {
    fetch(url)
      .then(response => response.json())
      .then(data => {
        result = items.find(
          item => item.id === 'abcd'
        );
      });
  };

  componentDidMount() {
    this._getData();
  }

  render() {
    return result ? <span>hello</span> : null;
  }
}

當我嘗試將result作為類的實例變量移動時,如下所示,它在render()方法中始終保持為 雖然任務在提取后正常工作:

import React, { Component } from 'react';

class MyData extends Component {
  result = null;
  _getData = () => {
    fetch(url)
      .then(response => response.json())
      .then(data => {
        this.result = items.find(
          item => item.id === 'abcd'
        );
      });
  };

  componentDidMount() {
    this._getData();
  }

  render() {
    return this.result ? <span>hello</span> : null;
  }
}

有人可以解釋我這里的預期用途是什么。 以及從 ES6 開始發生的變化。

這兩個示例都不起作用,原因是componentDidMount生命周期在render生命周期之后觸發

因為您不會在任何階段導致重新渲染(使用setState ),所以不會導致額外的渲染讀取result的更新值。

在此處輸入圖片說明

因此,下一個示例將始終呈現No Result

import ReactDOM from 'react-dom';
import React, { Component } from 'react';

let result = null;

class App extends Component {
  thisResult = null;
  setResult = () => {
    result = 10;
    this.thisResult = 10;
  };

  componentDidMount() {
    this.setResult();
  }

  render = () => {
    return <div>{result || this.thisResult ? 'Result' : 'No Result'}</div>;
  };
}

ReactDOM.render(<App />, document.getElementById('root'));

編輯華麗的雪花-u4s6x

您看到 null 的原因是因為您發布的代碼示例中未更新狀態。 組件掛載並且this.result為空。 但是當_getData方法被調用並且響應回來時,組件沒有被渲染。

您應該將這些數據存儲在您的狀態中,因為 React 依賴於狀態更改來知道何時應該重新渲染組件。 嘗試這樣的事情:

import React, { Component } from 'react';

class MyData extends Component {
  state = {
    result: null
  }
  _getData = () => {
    fetch(url)
      .then(response => response.json())
      .then(data => {
        this.setState({
          result: items.find(
            item => item.id === 'abcd'
          )
        })
      });
  };

  componentDidMount() {
    this._getData();
  }

  render() {
    const { result } = this.state
    return result ? <span>hello</span> : null;
  }
}

您可以在此處了解有關渲染、狀態和組件生命周期的更多信息: https : //reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class

編輯:如果您想嘗試使用新的 react hooks api,您可以將您的組件轉換為如下所示:

import React, { useEffect, useState } from 'react';

const MyData = ({ ...props }) => {
  const [result, setResult] = useState(null);

  const getData = () => {
    fetch(url)
      .then(response => response.json())
      .then(data => {
        const result = items.find(item => item.id === 'abcd');

        setResult(result);
      });
  };

  useEffect(() => {
    getData();
  }, []);

  return result ? <span>hello</span> : null;
}

我認為您缺少的主要內容是狀態。 請記住,您正在擴展的這些組件是具有非常特定生命周期的 React 組件類。 查看組件生命周期以獲取更多信息。 這將通過以下重構按預期工作:

import React, { Component } from 'react';

class MyData extends Component {
    constructor() {
        super();
        this.state = {result:  null};
    }

    _getData = () => {
        fetch(url)
        .then(response => response.json())
        .then(data => {
            let resp = data.items.find(
                item => item.id === 'abcd'
            );

            this.setState({ result: resp });
        });
    };

    componentDidMount() {
        this._getData();
    }

    render() {
       return this.state.result ? <span>hello</span> : null;
    }
 }

暫無
暫無

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

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