如何使用 mobx 将 promise 输出作为 prop 传递
How to pass promise output as prop using mobx
在我的 App.js 文件中,我有以下代码:
import stores from 'client/stores';
...
...
render() {
return (
<Provider {...stores}>
<SafeAreaView>
<AppContainer />
</SafeAreaView>
</Provider>
);
}
我想从后端检索我的数据并将其注入 AppContainer
。但是它必须使用承诺异步检索:
// 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);
})
其次,您应该仅在渲染函数中而不是构造函数中取消引用可观察对象 属性。
在我的 App.js 文件中,我有以下代码:
import stores from 'client/stores';
...
...
render() {
return (
<Provider {...stores}>
<SafeAreaView>
<AppContainer />
</SafeAreaView>
</Provider>
);
}
我想从后端检索我的数据并将其注入 AppContainer
。但是它必须使用承诺异步检索:
// 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);
})
其次,您应该仅在渲染函数中而不是构造函数中取消引用可观察对象 属性。