javascript - How to use @Action in Mobx + reactjs? - Stack Overflow

I am confused on how to use @action in my code.class Items {@observable items= [];@action addItem() {le

I am confused on how to use @action in my code.

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();

I am confused on how to use @action in my code.

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();
Share Improve this question edited May 19, 2017 at 1:32 Preview 35.8k10 gold badges95 silver badges113 bronze badges asked May 18, 2017 at 23:57 chobo2chobo2 86k207 gold badges551 silver badges862 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

Make sure that you alter this.items and not just items. You also need to bind either the action with action.bound or create a bound handler in the ponent:

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();

Or:

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();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744830385a4596048.html

相关推荐

  • javascript - How to use @Action in Mobx + reactjs? - Stack Overflow

    I am confused on how to use @action in my code.class Items {@observable items= [];@action addItem() {le

    2天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信