簡體   English   中英

反應待辦事項列表中的本地存儲

[英]Local storage in react todo list

我使用 react 創建了待辦事項列表,但我希望它是本地存儲 - 所以當用戶刷新頁面時,它仍然保存項目並顯示它們。 我讀到我需要使用 localStorage 但我不確定在何處以及如何附加 app.js 和 TodoItem 組件

class App extends Component {
  state = {
    items: [],
    id: uuidv4(),
    item: "",
    editItem: false
  };
  handleChange = e => {
    ...
  };
  handleSubmit = e => {
    e.preventDefault();
    const newItem = {
      id: this.state.id,
      title: this.state.item
    };
    const updatedItems = [...this.state.items, newItem];

    this.setState({
      items: updatedItems,
      item: "",
      id: uuidv4(),
      editItem: false
    });
  };
  ...
  render() {
    return (
            <TodoInput
              item={this.state.item}
              handleChange={this.handleChange}
              handleSubmit={this.handleSubmit}
              editItem={this.state.editItem}
            />
            <TodoList
              items={this.state.items}
              clearList={this.clearList}
              handleDelete={this.handleDelete}
              handleEdit={this.handleEdit}
            />
    );
  }
}
export default class TodoItem extends Component {
  state = {
    avatarURL: '',
  }

  componentDidMount() {
    imgGen().then(avatarURL => this.setState({ avatarURL }));
  }

  render() {
    const { title, handleDelete, handleEdit } = this.props;
    const { avatarURL } = this.state; 
    return (
        <h6>{title}</h6>
          <span className="mx-2 text-success" onClick={handleEdit}>
          </span>
          <span className="mx-2 text-danger" onClick={handleDelete}>
          </span>
    );
  }
}

你可以這樣做,注意評論

class App extends Component {
  state = {
    // load items while initializing
    items: window.localStorage.getItem('items') ? JSON.parse(window.localStorage.getItem('items')) : [],
    id: uuidv4(),
    item: "",
    editItem: false
  };
  handleChange = e => {
    // ...
  };

  handleSubmit = e => {
    e.preventDefault();
    const newItem = {
      id: this.state.id,
      title: this.state.item
    };
    const updatedItems = [...this.state.items, newItem];

    // Save items while changing
    window.localStorage.setItem('items', JSON.stringify(updatedItems));

    this.setState({
      items: updatedItems,
      item: "",
      id: uuidv4(),
      editItem: false
    });
  };
  // ...

  render() {
    return (
      <>
        <TodoInput
          item={this.state.item}
          handleChange={this.handleChange}
          handleSubmit={this.handleSubmit}
          editItem={this.state.editItem}
        />
        <TodoList
          items={this.state.items}
          clearList={this.clearList}
          handleDelete={this.handleDelete}
          handleEdit={this.handleEdit}
        />
      </>
    );
  }
}

這是您可以在App componentDidMount()方法中使用的一些簡單邏輯。

const localStorageList = localStorage.getItem('todo-list')

if (!localStorageList) {return null} else {this.setState({items: localStorageList})

要添加到 localStorage 請看這個問題

這個資源

讓我幫您解決這個問題,至少不要使用。 的代碼。 步驟我已經寫得很清楚了,為了讓大家更好的理解,還請大家耐心看完,絕對是跟讀的時間。

另請注意,此解決方案是為功能組件完美打造的。 但是我已經提到如何在類組件中做到這一點,如果您使用類組件,則必須調整一些東西。 就像您不能在基於類的組件中使用鈎子一樣,但可以訪問此實例,因此無論哪種方式都可以

請仔細閱讀,如果您在理解功能方面遇到困難,我已嘗試在外行人中分解該過程。 解釋很長,代碼行數不到 10 行。樂於助人

在頁面刷新時保持待辦事項應用程序的狀態非常簡單。 我們可以為它使用狀態管理庫,也可以使用本地存儲。 在這里,我們將使用最簡單的方法——使用本地存儲。

在我們跳轉到代碼之前,讓我們直觀地構建功能。 因此,在用戶在待辦事項空間輸入內容后,我們希望發生的事情很少:

  1. 我們想將項目列表(本質上是一個數組)存儲在本地存儲中。 (我們可以跳過JSON.parse,這里因為要保存的數組是字符串,bcz用戶在todo-app中輸入字符串,但一般來說,解析用戶輸入並不是一個壞主意)。

 useEffect(()=>{ window.localStorage.setItems("key" , value) }, [dependency])

執行此操作后,請確保檢查 dev-tools => application => localStorage => 以查看是否正在存儲鍵和值。 你將能夠看到它們。 但是,您會注意到,刷新后,localStorage 值保留,但 UI 中的數據丟失。 不奇怪。

  1. 這是最后一步也是重要的一步。 頁面重新加載時我們想要什么? 讓我們分解一下:
  • 我們想檢查 localStorage 中是否有任何數據。 如果有:我們將根據之前的用戶輸入更改應用程序的狀態。

  • 如果 LocalStorage 中沒有數據,我們將只傳遞一個空數組。

使用鈎子,在功能組件中實際上是我更喜歡的,類組件需要很多樣板,所以,代碼......

 import {useState} from 'react';/for functional components //for class components you can just init the state , in the constructor(props) and change it using the this.setState method //to getItems from localStorage to render in the UI useEffect(()=>{ const storedData = localStorage,getItems("keys" , value) storedData ? setValue(value) : []; },[]) [] : because we want it to render on every reload, once. smake sure to initiliaze the state using useState; const [value , setValue] = useState("") //to setItems in localStorage useEffect(()=>{ window.localStorage.setItems("key" , value) }, [dependency])

useEffect 本質上是一個功能組件的鈎子,類似於 componentDidMount 類內組件。 如果使用類組件,請使用 this.setState,而不是使用 useState 鈎子。

您可以將您的 todolist 格式化為 JSON 字符串並使用以下命令存儲它:

localStorage.setItem("todolist", "your_JSON_string_here");

但是,Web 本地存儲具有存儲限制,如果存儲的數據及時變大,則會導致問題。 更多信息在這里

也許您可以考慮 IndexedDB(如果您要存儲大量數據) INFO

暫無
暫無

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

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