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”字符串),控制台中没有错误。我该如何修复和调试它?使用“调试器”关键字没有显示任何可观察的内容。

4

1 回答 1

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}>.

于 2017-02-16T13:36:41.770 回答