2017-05-18 15 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それは本当に好みになるだけです。私は自分のコンポーネントにハンドラーを作成する傾向があります。後でアクションを呼び出すだけではなく、通常はオプション2を使用します。 – Tholle

+0

何らかの理由がありますが、ちょうどそのように見えますが、実際には何の利益も見られません。私はまた、コンポーネント自体に@actionを置く第3のオプションを見た。 – chobo2

関連する問題