2017-08-13 32 views
0

我在我的反应原生项目中使用axiosmobx。其中一个安装组件(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相关的东西了吗?

+0

'@inject('BirdStore')@ observer'只能在React组件上使用,而不能在像'api'这样的常规对象上使用。还可以尝试更改'Home“上的装饰器的顺序。 '@inject(“BirdStore”)@ observer' – Tholle

+1

@Tholle好的。感谢您的领导! –

回答

0

这个错误很神秘。他们说:“必须依附......”。鉴于此,我会说,是的。您需要将装饰器附加到类中。但更重要的是,否则您将无法访问this.props

+0

啊!是的,'this.props'。任何方式,我希望有一种方式。 –

+0

为什么不在商店中定义你的'''getBirds()'''api作为@action调用?我就是这么做的 – archae0pteryx

+0

是的。我认为这样好多了。但是,如何将错误从catch()传递到Home组件。或者我应该让另一个可观察的变量来保存错误?任何想法? –

相关问题