2017-05-18 39 views
1

我很困惑如何在我的代码中使用@action。如何在Mobx + reactjs中使用@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

请确保您改变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(); 
+0

是@ action.bound推荐的更办法吗?似乎如果你不使用它,重复一个没有真正收益的​​方法? – chobo2

+0

@ chobo2它真的只是归结于偏好。我个人倾向于在我的组件上创建处理程序,如果我需要做的不仅仅是后来的行动,所以我通常选择两项。 – Tholle

+0

任何理由为什么,因为它看起来像更多的工作,但没有看到真正的任何收益。我还看到了第三个选项,他们将@action放在组件本身中。 – chobo2