我使用 mobx 的代码不会更新状态

问题描述 投票:0回答:1

我有一个简单的代码,我是 mobx 的新手,它在上下文中更容易,但我必须使用 mobx :

import { makeAutoObservable } from "mobx";
import booksRepository from "../Books/Books.repository";

class BookStore {
  books = [];
  showPrivateBooks = false;

  constructor() {
    makeAutoObservable(this);
  }

  async loadBooks() {
    const books = await booksRepository.getBooks(this.showPrivateBooks);
    this.books = [...books];
  }

  async addBook(newBook) {
    await booksRepository.addBook(newBook);
    await this.loadBooks();
  }

  async toggleShowPrivateBooks() {
    this.showPrivateBooks = !this.showPrivateBooks;
    await this.loadBooks();
  }
}

const bookStore = new BookStore();
export default bookStore;

和index.js:

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react";
import bookStore from "./Store/BookStore";

import "./styles.css";

function App() {
  useEffect(() => {
    bookStore.loadBooks();
  }, []);

  const handleAddBook = async () => {
    const newBook = {
      name: "Book",
      ownerId: "postnikov",
      author: "Someone",
    };
    await bookStore.addBook(newBook);
  };

  return (
    <div>
      <div>
        <button onClick={() => bookStore.toggleShowPrivateBooks()}>
          {bookStore.showPrivateBooks ? "Show All Books" : "Show Private Books"}
        </button>
      </div>
      {bookStore.books.map((book, i) => (
        <div key={i}>
          {book.author}: {book.name}
        </div>
      ))}
      <button onClick={handleAddBook}>Add</button>
    </div>
  );
}

const ObservedApp = App;

const rootElement = document.getElementById("root");
ReactDOM.render(<ObservedApp />, rootElement);


但是,切换按钮不起作用。

看起来商店正在更新,但屏幕上的数据没有变化 一旦我按下按钮,商店就会更新,新数据会加载,但用户界面不会改变

您可以在这里找到完整的代码codesandbox

reactjs mobx
1个回答
0
投票

您需要用

App
HOC 包装您的
observer
(基本上每个使用 MobX 存储中的数据的组件):

import { observer } from "mobx-react";

const App = observer(...)

https://mobx.js.org/react-integration.html#react-integration

© www.soinside.com 2019 - 2024. All rights reserved.