react getting observable values in component

别等时光非礼了梦想. 提交于 2019-12-12 03:09:14

问题


Seting the obsrv array in the component below;

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) => {
      });
  }
}

I checked the retrieved values its ok. and I try set it in component and render it below;

@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>
    );
  }
}

I expected to see all list items but none(only "listItems" string)in html, no error in console. how can I fix and debug it ? using "debugger" keyword shows nothing for observable.


回答1:


In your code, I don't see where are you creating the instance of AnnouncementState. Here an example how can you get the categories list.
e.g.

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>
    );
  }
}

This should work, just be sure you pass the correct store with <Provider store={store}>.



来源:https://stackoverflow.com/questions/42268727/react-getting-observable-values-in-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!