簡體   English   中英

將反應 class 轉換為反應鈎子 useState?

[英]convert react class to react hooks useState?

有人可以幫我把它轉換成反應鈎子嗎我相信它會反應 useState()

https://github.com/react-grid-layout/react-grid-layout/blob/master/test/examples/7-localstorage.jsx

import React from "react";
import RGL, { WidthProvider } from "react-grid-layout";

const ReactGridLayout = WidthProvider(RGL);
const originalLayout = getFromLS("layout") || [];
/**
 * This layout demonstrates how to sync to localstorage.
 */
 export default class LocalStorageLayout extends React.PureComponent {
 static defaultProps = {
 className: "layout",
 cols: 12,
 rowHeight: 30,
 onLayoutChange: function() {}
};

  constructor(props) {
    super(props);

    this.state = {
      layout: JSON.parse(JSON.stringify(originalLayout))
    };

    this.onLayoutChange = this.onLayoutChange.bind(this);
    this.resetLayout = this.resetLayout.bind(this);
  }

  resetLayout() {
    this.setState({
      layout: []
    });
  }

  onLayoutChange(layout) {
    /*eslint no-console: 0*/
    saveToLS("layout", layout);
    this.setState({ layout });
    this.props.onLayoutChange(layout); // updates status display
  }

  render() {
    return (
      <div>
        <button onClick={this.resetLayout}>Reset Layout</button>
        <ReactGridLayout
          {...this.props}
          layout={this.state.layout}
          onLayoutChange={this.onLayoutChange}
        >
          <div key="2" data-grid={{ w: 2, h: 3, x: 8, y: 0 }}>
            <span className="text">5</span>
          </div>
        </ReactGridLayout>
      </div>
    );
   }
}

function getFromLS(key) {
  let ls = {};
   if (global.localStorage) {
    try {
      ls = JSON.parse(global.localStorage.getItem("rgl-7")) || {};
    } catch (e) {
      /*Ignore*/
    }
  }
  return ls[key];
 }

 function saveToLS(key, value) {
  if (global.localStorage) {
   global.localStorage.setItem(
    "rgl-7",
      JSON.stringify({
      [key]: value
    })
  );
 }
}

 if (process.env.STATIC_EXAMPLES === true) {
 import("../test-hook.jsx").then(fn => fn.default(LocalStorageLayout));
}

盡我所能理解反應類,因為我只知道反應鈎子,所以任何耐心的幫助都會非常棒和有幫助,請謝謝

如果您了解組件的生命周期,則 React 類很簡單。 一個組件被實例化,然后被掛載(與 DOM 相關聯),然后它被渲染。
每次更新(狀態或道具)后,它都會重新渲染。

構造函數
組件或任何 JS class 的實例化發生在constructor中。 它只運行一次 由於 class 組件繼承自React.Component ,它們通過調用super(props)將 props 傳遞給React.Component 這會初始化props字段。 super調用應該是構造函數中的第一行。
不能在構造函數中訪問以下內容: windowdocumentfetchlocalStoragesessionStorage

使成為
render 方法返回渲染的Element / Fragment 它對應於 function 組件的返回部分。 每次渲染組件時它都會運行。

事件監聽器綁定
類中最難的部分是事件方法綁定。
隱含的this object,是訪問 state、props 和其他組件方法所必需的。 但是,在事件偵聽器方法*. 它指的是事件目標 因此bind調用。 盡管如此,這個問題可以通過使用箭頭方法繞過,因為箭頭函數沒有自己的this (即this不引用事件目標)。
Function 組件沒有這個問題,因為他們不需要this

State
state 在構造函數中初始化。
與 function 組件不同,類將 state 視為單個 object
代替,

let [x, setX] = useState(0); let [y, setY] = useState(1);

在課堂上是:

this.state = {x:0, y:1};

為了更新 state,我們使用setState方法,

this.setState({x: 3}); // updates only x, & y is unchanged: setX(3)
this.setState({x: 3, y: 4}); // updates both x & y: setX(3); setY(4)
this.setState((state)=>({ y: state.y - 1)) // updates y using previous value: setY(y=>y-1)

類的一個優點是我們可以使用另一個state 屬性的先前值來更新 state 屬性。

this.setState((state)=>({x: (y%2)? 100: 50})); // updates x using y's value

此外,state 可以針對道具進行更新:

this.setState((state,props)=>({x: state.x + props.dx}));

此外, setState有一個可選的第二個回調參數 此回調在 state 更新立即運行。

this.setState(state=>({x: state.x+1}), ()=> {
    // called after x is updated
    sessionStorage.setItem('x', this.state.x);
});

// function version
setX(x=>x+1);

useEffect(()=> {
    localStorage.setItem('x', x);
}, [x]); // runs every time x is updated   

安裝
掛載后,調用componentDidMount() 現在,組件可以訪問windowdocument對象。
在這里,你可以

  • 調用setInterval / setTimeout
  • 使用 API 調用 ( fetch ) 或存儲 ( localStorage & sessionStorage ) 更新 state

相當於useEffect(()=> {}, [])

卸載

在卸載componentWillUnmount()之前被調用。 通常,此處調用clearTimeout / clearInterval清理組件。

它相當於useEffect的返回方法。

useEffect(()=>{
    //....
    return ()=> {
        // componentWillUnmount code
    };
}, [])

暫無
暫無

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

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