我对如何在代码中使用@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();
答案 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();