首页 > 解决方案 > 如何使用 mobx 将承诺输出作为道具传递

问题描述

在我的 App.js 文件中,我有以下代码:

  import stores from 'client/stores';
  ...
  ...
  render() {
     return (
        <Provider {...stores}>
          <SafeAreaView>
            <AppContainer />
          </SafeAreaView>
       </Provider>
     );
  }

我想从后端检索我的数据并将其注入AppContainer. 但是,它必须使用 promise 异步检索:

// client/stores/index.js

boardsService.retrieveBoards().then(boards => {
    // I need to store boards here 
})

然后将板注入我的AppContainer

export default
@inject('boards')
@observer
class AppContainer extends React.Component {
  constructor(props) {
     super(props);
     console.log(props.boards); 
  }

  render() {
     ...
  }
}

我在stores/index.js 中试过这个:

async function connect() {
  const connection = await boardsService.retrieveBoards();
  if (connection) {
    return connection;
  }
  return null;
}

connect().then(boards => {
  exports.boards = boards;
}); 

但我得到这个错误:

在此处输入图像描述

标签: javascriptreact-nativemobxmobx-reactstate-management

解决方案


首先,Mobx 中的 Actions 没有返回值。他们只是改变了可观察的属性。动作是同步的还是异步的都没有关系。

@observable boards = [];

boardsService.retrieveBoards().then(boards => {
 this.boards.replace(boards);
})

其次,您应该只在渲染函数中取消引用 observable 属性,而不是在构造函数中。


推荐阅读