2017-02-09 27 views
1

当我使用mobx-react,我用注入的装饰,当我拿到店里如如何使用@inject绑定函数?

@inject("store") @observer 
class item extends Component { 
    constructor() { 
    this.store = this.props.store; 
    } 
} 

但是,当我想打电话给如store.getUser()store的功能,我发现传输store.But的上下文getUser函数不是this,我怎样才能将this绑定到store

PS:在商店如下列:

class Store { 
    @observable user = "Sarah"; 
    @computed 
    get getUser() { 
    return user + "Ok"; 
    } 
} 
export default new Store(); 

我使用getUser

render() { 
    <div>{this.store.getUser()}</div> 
} 
+0

你可以添加你调用'getUser'的代码吗? –

回答

1

您的商店使用this.user

class Store { 
    @observable user = "Sarah"; 
    @computed 
    get getUser() { 
    return this.user + "Ok"; 
    } 
} 
export default new Store(); 

一个computed是一个getter,所以你不能通过函数调用来访问它。只是取消引用领域:

render() { 
    <div>{this.store.getUser}</div> 
} 
+0

哦,对不起,这是我的lapsus calami,我在我的代码中使用了'this.user'。 –

+0

@YingchXue我明白了。你可以在你的代码中添加其余的'Component'吗? – Tholle

+0

哦,非常感谢! –

1
class Store { 
    @observable user = "Sarah"; 
    @computed 
    get okUser() { 
    return this.user + "Ok"; 
    } 
} 

const store = new Store(); 
console.log(store.okUser); 

@computed是吸气,所以你不需要调用它的功能。

+0

谢谢!我是js的新手 –

相关问题