在构造函数

时间:2016-12-30 03:44:59

标签: javascript android reactjs react-native

我刚刚接受了本地反应,但真的陷入了场景#2和#3。这可能是一小时的迟到,但我不能让listview重新填充场景的构造函数之外......

注意:这是一个简单的示例,最终将成为更高级的数据加载

场景#1在控制器中绑定

这很有效:

export default class HomeView extends Component {
  constructor(props)
  {
    super(props);

    const ds = new ListView.DataSource(
      {
        rowHasChanged: (r1,r2) => r1 !== r2
      }
    );

    var data = [
        {"id":1, "desc": "Some description of a request", "group": "Today"},
        {"id":2, "desc": "Another description of a request", "group": "Today"} 
      ];

    this.state = {
      loaded: false,
      data: data,
      dataSource: ds.cloneWithRows(data)
    };

场景#2 - 调用加载方法

此子集从构造函数开始。当我直接调用该方法时,它会产生“在未安装的组件上调用setState是一个问题”错误。很公平,但它完成所有方法并运行两个控制台语句。我试图在#3中解决这个问题。

    var data = [
        {"id":1, "desc": "Some description of a request", "group": "Today"},
        {"id":2, "desc": "Another description of a request", "group": "Today"} 
      ];

    this.state = {
      loaded: false,
      data: data,
      dataSource: ds
    };

     console.log("About to load data");
     this.loadData();
   } //end ctor

   loadData() {
     console.log("Data count is: " + this.state.data.length);

     this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.state.data),
        loaded     : true
     });
   }

场景#3 - 使用绑定

对LoadData使用Bind()方法只会留下空白屏幕而不显示日志记录语句,因此它以另一种方式进行了冲洗。代码从构造函数中开始......

 var data = [
    {"id":1, "desc": "Some description of a request", "group": "Today"},
    {"id":2, "desc": "Another description of a request", "group": "Today"} 
  ];

 this.state = {
   loaded: false,
   data: data,
   dataSource: ds
 };

  console.log("About to load data");
   this.loadData = this.loadData.bind(this);
} //end ctor

loadData() {
   console.log("Data count is: " + this.state.data.length);

   this.setState({
     dataSource: this.state.dataSource.cloneWithRows(this.state.data),
     loaded     : true
   });
}

我如何使这项工作?

2 个答案:

答案 0 :(得分:0)

使用const关键字并声明类的外部

const data = [
        {"id":1, "desc": "Some description of a request", "group": "Today"},
        {"id":2, "desc": "Another description of a request", "group": "Today"} 
      ];

答案 1 :(得分:0)

我以为我早点尝过,但显然我没有正确使用它。该场景有一些可用的内置方法:componentWillMount()在调用render()方法之前运行,在安装组件之前运行,componentDidMount()在render()之后和安装之后运行,所以在componentDidMount()中这样做现在有效:

componentDidMount() {
    var data = [
        {"id":1, "desc": "Some description of a request", "group": "Today"},
        {"id":2, "desc": "Another description of a request", "group": "Today"} 
      ];

    console.log("Loading data...");

    this.setState({
        dataSource: this.state.dataSource.cloneWithRows(data),
        loaded     : true
    });
  }