使用react-mobx重新发送异步提取

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

我正在尝试将mobx-restmobx-rest-axios-adaptermobx-react一起使用,并且我无法在异步数据检索时使组件重新渲染。

这是我的数据模型,在state/user.js

import { Model } from 'mobx-rest';

class User extends Model {
  url() {
    return '/me';
  }
}

export default new User();

这是React组件,在App.js中:

import React from 'react';
import { inject, observer } from 'mobx-react';
import { apiClient } from 'mobx-rest';
import createAdapter from 'mobx-rest-axios-adapter';
import axios from 'axios';
import { compose, lifecycle, withProps } from 'recompose';

const accessToken = '...';
const API_URL = '...';

const App = ({ user }) => (
  <div>
    <strong>email:</strong>
    {user.has('email') && user.get('email')}
  </div>
);

const withInitialise = lifecycle({
  async componentDidMount() {
    const { user } = this.props;

    const axiosAdapter = createAdapter(axios);
    apiClient(axiosAdapter, {
      apiPath: API_URL,
      commonOptions: {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      },
    });

    await user.fetch();

    console.log('email', user.get('email'));
  },
});

export default compose(
  inject('user'),
  observer,
  withInitialise,
)(App);

它使用recomposeuser中的API异步获取componentDidMount(),一旦可用,该组件应该显示用户电子邮件。 componentDidMount()打印一次可用的电子邮件。

最后这是index.js

import React from 'react';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import { Provider } from 'mobx-react';
import { RouterStore, syncHistoryWithStore } from 'mobx-react-router';
import { Router } from 'react-router';

import App from './App';
import { user } from './state/user';

const documentElement = document.getElementById('ReactApp');

if (!documentElement) {
  throw Error('React document element not found');
}

const browserHistory = createBrowserHistory();
const routingStore = new RouterStore();

const stores = { user };
const history = syncHistoryWithStore(browserHistory, routingStore);

ReactDOM.render(
  <Provider {...stores}>
    <Router history={history}>
      <App />
    </Router>
  </Provider>,
  documentElement,
);

我的问题是,一旦检索到用户并且电子邮件可用,组件就不会重新呈现,尽管控制台日志显示它在异步请求中返回正常。我试过玩mobx-react的computed,但没有运气。有任何想法吗?

asynchronous mobx mobx-react
1个回答
1
投票

我认为如果你更改App.js的撰写顺序,它会起作用:

export default compose(
  inject('user'),
  withInitialise,
  observer,
)(App);

根据MobX official document

提示:当观察者需要与其他装饰器或更高阶的组件组合时,请确保观察者是最里面的(第一个应用的)装饰器;否则它可能什么都不做。

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