当存储中的值更改时,react-mobx @ 6组件不会重新呈现

时间:2020-03-05 00:18:28

标签: reactjs mobx mobx-react

我正在尝试第一次使用react-mobx。我一直遵循https://mobx-react.js.org/recipes-context#multiple-global-stores来创建组件。

下面是代码。在App中进行ajax调用。当ajax调用失败时,将在uiStore中设置一条错误消息,并且ErrorAlert组件应重新呈现。运行此代码时,我看到该错误在ajax调用中被击中,并且该错误在uiStore中设置。如果我uiStore.error,我看到console.log(uiStore)已更新。但是由于某些原因,即使将ErrorAlert包装在observer中,也不会重新呈现它。我在做什么错了?

谢谢!

uiStore:

import { observable, action } from "mobx";

class UiStore {
  @observable error = undefined;
  @action setError = (error) => {
    this.error = parseError(error);
  };
}
export default new UiStore();

storesContext:

import React from "react";
import uiStore from "../stores/uiStore";

export const storesContext = React.createContext({
  uiStore
});

useStores挂钩:

import React from "react";
import { storesContext } from "../contexts";

export const useStores = () => React.useContext(storesContext);

应用程序:

import React, { useEffect } from "react";
import { useStores } from '../hooks/useStores';

import { ErrorAlert } from '../ErrorAlert';

export const App = props => {
  const { uiStore } = useStores();
  useEffect(() => {
    loadUser();
  }, []);

  const loadUser = () => {
    $.ajax({
      url: '/some-endpoint',
      method: "GET",
      dataType: "json",
      contentType: "application/json",
      success: () => {
        ...
      },
      error: e => {
        uiStore.setError(e);
      }
    });
  };

  return (
    <>
      <ErrorAlert />
    </>
  );
}

ErrorAlert

import React from "react";
import { observer } from 'mobx-react';
import { useStores } from '../hooks/useStores'

export const ErrorAlert = observer(props => {
  const { uiStore } = useStores();

  return <div>{uiStore.error}</div>;
});

0 个答案:

没有答案