【问题标题】:React-Native ListView not loading data correctlyReact-Native ListView 未正确加载数据
【发布时间】:2017-02-04 20:20:51
【问题描述】:

我有一个包含字符串列表的列表视图。最初,从中获取行的数组应该是空的,但只是为了测试它,我在其中提供了数据。然而它没有出现。它仅在调用 lapPressed 时显示,该调用旨在使用新字符串向表中添加一行。并且只有在我再次按下按钮时才会添加新字符串。这个循环并且只有在再次调用 lapPressed 时才会添加最新的数据。

回顾一下:

  • 在调用 lapPressed 之前,不会显示数组 laps 的初始元素
  • 在两次调用 lapPressed 之前不会显示新行

我已经删除了不相关的代码, 这是我的代码:

  constructor(props) {
    super(props);

    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    //dataSource: this.state.dataSource.cloneWithRows(this.state.laps)

    this.state = {
      laps: [2,3],
      dataSource: ds.cloneWithRows(this.laps),
    }
  }


  render() {
    return <View>

        {this.showList()}

    </View>
  }


  showList() {
    return <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderRow.bind(this)}
      />
  }

renderRow(rowData, sectionID, rowID) {
    return (
      <View style={styles.row}>
      <Text style={styles.rowText} numberOfLines={1}>{rowData}</Text>
      </View>
    );
  }


lapPressed = () => {

    var lap = formatTime(this.state.timeElapsed);

    this.setState({
      startTime: new Date(),
      laps: this.state.laps.concat([lap]),
      dataSource: this.state.dataSource.cloneWithRows(this.state.laps)
    });
    return

  }

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    这是你的问题:

    this.state = {
      laps: [2,3],
      dataSource: ds.cloneWithRows(this.laps),
    }
    

    this.laps 未定义。它应该是this.state.laps,但这里也没有分配。我想这就是你需要的:

    var laps = [2, 3];
    
    this.state = {
      laps: laps,
      dataSource: ds.cloneWithRows(laps),
    }
    

    【讨论】:

    • 这使得第一个元素出现在启动时,但第二个问题仍然存在。当我调用 lapPressed 时,什么都没有更新,当我再次按下它时它会更新,它总是落后。
    • 同样的问题。您的cloneWithRows 电话会获取上一圈的值。 this.state.laps 尚未更新。
    • 谢谢,我只是同时想出来的 :)
    【解决方案2】:

    这是因为我在 lapPressed 中提供了旧状态,这是正确的版本。

    lapPressed = () => {
    
        var lap = formatTime(this.state.timeElapsed);
        var temp = this.state.laps.concat([lap])
    
        this.setState({
          startTime: new Date(),
          laps: temp,
          dataSource: this.state.dataSource.cloneWithRows(temp)
        });
    
        return
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      相关资源
      最近更新 更多