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();
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 component:
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With