我在我的反应原生项目中使用axios
和mobx
。其中一个安装组件(Home
)需要从其他所有API方法组织的文件中调用方法(getBirds()
)。如何使用mobx observer而无需使用类中的反应
store.js:
class BirdStore {
@observable birdList = [];
@action setBirdList = (birds) => {
this.birdList = birds;
};
}
Home.js:
@observer @inject("BirdStore")
export default class Home extends React.Component {
componentDidMount() {
api.getBirds()
...
}
}
api.js:
@inject('BirdStore') @observer
const api = {
getBirds() {
const url = website + '/api/birds/';
return axios.get(url)
.then((response) => {
this.props.BirdStore.setBirdList(response.data)
})
.catch((error) => {
console.log(error);
})
},
};
但是,这给了我一个错误:
Leading decorator must be attached to a class declaration
我可以使用由getBirds()
返回的服务器中的数据到Home
组件,然后调用setBirdList()
动作,但我想分开保留api相关的东西。无论如何,如果没有这个类,我可以使用mobx
,这样我就可以处理除类组件本身之外的所有api相关的东西了吗?
'@inject('BirdStore')@ observer'只能在React组件上使用,而不能在像'api'这样的常规对象上使用。还可以尝试更改'Home“上的装饰器的顺序。 '@inject(“BirdStore”)@ observer' – Tholle
@Tholle好的。感谢您的领导! –