1

When I use the mobx-react ,I use inject decorator to transmit the store.But when I get the store such as

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

But when I want to call the function of store such as store.getUser() , I found that the context getUser function is not this , how can I bind this to the store ?

PS: the store is such as following :

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

I use the getUser like

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

2 回答 2

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

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

@computed是吸气剂,因此您不需要将其称为函数。

于 2017-02-10T06:40:14.437 回答
1

您必须this.user在您的商店中使用:

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

Acomputed是一个吸气剂,因此您不能通过函数调用来访问它。只需取消引用该字段:

render() {
  <div>{this.store.getUser}</div>
}
于 2017-02-09T09:57:04.467 回答