如何在Mobx + reactjs中使用@Action?

时间:2017-05-18 23:57:36

标签: javascript reactjs mobx mobx-react

我对如何在代码中使用@action感到困惑。

class Items {

  @observable items= [];

  @action addItem() {
    let newItem= new Item();
    items.push(newItem);
  }
}

@observer
class ItemPage extends Component {

  constructor() {
    super();
  }

  render() {
    const {addItem} = this.props.store;
    return (
      <div className="items">
        <input type="button" value="add" onClick={addItem}/>
      </div>
    )
  }
}

const store = new Items();

1 个答案:

答案 0 :(得分:4)

确保您改变this.items而不仅仅是items。您还需要将操作与action.bound绑定,或在组件中创建绑定处理程序:

class Items {
  @observable items= [];

  @action.bound
  addItem() {
    let newItem = new Item();
    this.items.push(newItem);
  }
}

@observer
class ItemPage extends Component {
  render() {
    const { addItem } = this.props.store;
    return (
      <div className="items">
        <input type="button" value="add" onClick={addItem}/>
      </div>
    );
  }
}

const store = new Items();

或者:

class Items {
  @observable items= [];

  @action
  addItem() {
    let newItem = new Item();
    this.items.push(newItem);
  }
}

@observer
class ItemPage extends Component {
  handleClick = () => {
    this.props.store.addItem();
  };
  render() {
    return (
      <div className="items">
        <input type="button" value="add" onClick={this.handleClick}/>
      </div>
    );
  }
}

const store = new Items();