2017-02-16 24 views
0

下のコンポーネントでobsrv配列を設定します。コンポーネント内で観測可能な値が得られます

class AnnouncementState { 
    @observable categories =[]; 
    constructor(){ 
     this.getAnnouncementCategory(); 
    } 

    getAnnouncementCategory() { 
    fetch(`..`) 
     .then((response) => { 
     return response.json(); 
     }) 
     .then((response) => { 
     this.categories = response.value.map((item , i)=>{ return {Id:item.Id, Title:item.Title} }); 
     }, (error) => { 
     }); 
    } 
} 

検索した値を確認しました。私はコンポーネントでそれを設定しようとし、それを下にレンダリングします。

@observer 
class AnnouncementComponent extends React.Component { 
    categories = []; 
    componentWillMount(){ 
    debugger 
    this.categories=this.props.announcement.categories; 
    } 

    render() { 
    const listItems = this.categories.map((item) => { 
     return (<li>...</li>) 
    }); 

    return (
      <div id="announcements-tab"> 
      List Items: 
      <ul className="nav nav-tabs"> 
       {listItems} 
      </ul> 
      </div> 
    ); 
    } 
} 

私は、HTMLでコンソールにはエラーをすべてリスト項目が、どれも(のみ「のlistItems」の文字列を)見ないと予想。どのように修正してデバッグできますか? "debugger"キーワードを使用すると、観測可能なものは何も表示されません。

答えて

2

コードでは、どこにAnnouncementStateのインスタンスを作成しているのかわかりません。ここでは、どのようにカテゴリリストを得ることができるかの例を示します。

class AnnouncementState { 

    @observable categories =[]; 

    @action getAnnouncementCategory() { 
     fetch(`..`) 
      .then((response) => { 
     return response.json(); 
      }) 
      .then((response) => { 
     this.categories = response.value.map((item , i)=>{ return {Id:item.Id, Title:item.Title} }); 
      }, (error) => { 
      }); 
     } 
} 

export default new AnnouncementState(); //here you can create the instance. 


@observer 
@inject('store') //here substitute with your store name, the name you set in your provider 
class AnnouncementComponent extends React.Component { 

    componentWillMount(){ 
    debugger 
    this.props.store.getAnnouncementCategory(); 
    } 

    render() { 
    const listItems = this.props.store.categories.map((item) => { 
     return (<li>...</li>) 
    }); 

    return (
      <div id="announcements-tab"> 
      List Items: 
      <ul className="nav nav-tabs"> 
       {listItems} 
      </ul> 
      </div> 
    ); 
    } 
} 

これはちょうどあなたが<Provider store={store}>で正しいストアを渡すことを確認し、動作するはずです。

+0

"@inject( 'store')"私はこれがいくつかの場所に物を注入するのを見ます、なぜ私はそれを必要としますか?それは依存性注入のためですか?私は注射を使用しませんでしたが、私のコードはまだ動作しますので、いつ必要ですか? – TyForHelpDude

+2

例えば、コンポーネントを別のコンポーネントの中に入れて、店舗を通ることを避けるために、プロバイダを使用してストアを渡し、その特定のコンポーネントでインスタンスを取得するだけです。 – Hosar

関連する問題