javascript - 如何使用 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;
});
但我得到这个错误:
解决方案
首先,Mobx 中的 Actions 没有返回值。他们只是改变了可观察的属性。动作是同步的还是异步的都没有关系。
@observable boards = [];
boardsService.retrieveBoards().then(boards => {
this.boards.replace(boards);
})
其次,您应该只在渲染函数中取消引用 observable 属性,而不是在构造函数中。
推荐阅读
- flutter - 如何在颤动中限制onLocationChanged
- karate - 有没有办法查看架构验证失败的地方?
- python - 如何在 anaconda 中添加共享库?
- node.js - 无服务器 & aws lambda & puppeteer & Node.js
- visual-studio-code - vscodevim:闲置一段时间后,
在命令行中返回“正常”模式或明文 - json - Jmeter Json Extractor:JSONPath 表达式适用于评估器,但不适用于 jmeter?
- mysql - ORDER BY RAND() 和大表的问题
- javascript - 如何升级lerna分包的node模块
- python - Django 表单 - 自动填写表单的用户 url attr - RelatedObjectDoesNotExist
- c - 程序无法接收第二个输入