在 React Native 中枚举 ListView 时遇到问题

Having trouble enumerating a ListView in React Native

我刚开始使用 React JS,所以我不习惯语法。

基本上,长话短说,我不知道将 number++ 迭代器放在哪里。我希望每次在我的 this.state = {rank:number}

中添加新的列表项行时,我的数字都会增加

这应该很简单,但我似乎无法弄清楚如何将数字迭代函数插入到我的 ListView 中。请帮忙!

此外,如果您还知道如何按分数对 ListView 进行排序,那将对我的项目有很大帮助。我洗耳恭听。

这是我的代码:

const users = [
  {id:1, name: "Jerry Love", score: 12},
  {id:2, name: "Bob Billy", score: 10},
  {id:3, name: "Santana Diego", score: 1},
  {id:4, name: "Thompson Merlin", score: 6},
  {id:5, name: "Harold Davis", score: 3},
  {id:6, name: "Raritan Junior", score: 9},
  {id:7, name: "Caroline Anderson", score: 19},
  {id:8, name: "Haly Edison", score: 14},

]

class GlobalRankView extends Component {
  constructor(props){
    super(props)
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
    this.state = {
      rank: number,
      matchedusersDataSource: ds.cloneWithRows(users)
    }
  }

  render() {
    return (
      <View style={styles.rankingContainer}>
        <View style={styles.rankingHeaderRow}>
          <Text style={styles.headerText}>Rank</Text>
          <Text style={styles.headerText}>User</Text>
          <Text style={styles.headerText}>Trophies</Text>
        </View>
        <ListView
          dataSource={this.state.matchedusersDataSource}
          renderRow={(user) => { return this.renderuserRow(user) }}
        >
        </ListView>
      </View>
    )
  }

  renderuserRow(user) {
    return(
      <View style={styles.userRow}>
        <Text>{this.state.rank}</Text>
        <View styles={styles.userColumn}>
          <Text style={styles.userName}> {user.name}</Text>
          <Text style={styles.userDistance}> {user.score}</Text>
        </View>
      </View>
    )
  }
}

你的问题不是关于使用 react-nativeListView,你基本上是对 React 中的 stateprops 的概念有问题。

据我了解,您是说您有一个项目列表,您可以在其中添加其他项目。首先,我会让 state 更简单:

this.state = {
  users
}

您的 state 中不需要 rank,因为它可以使用 this.state.users.length 计算得出。因此你可以这样做:

在你的 renderUserRow:

// Change this
<Text>{this.state.rank}</Text>
// For
<Text>{this.state.users.length}</Text>

在您的 render() 函数中:

render() {
  return (
    ...
    const data = dataSource.cloneWithRows(this.state.users)
    <ListView
       dataSource={data}
       renderRow={(user) => { return this.renderuserRow(user) }}
    >
    ...

奖励点 1:您可以在组件外部定义:

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

注意id比较,这会让你的生活更轻松。

奖励点 2:您不想每次重新渲染时都使用 cloneWithRows?查看 https://github.com/reactjs/redux/issues/683(尽管我怀疑这会是一个问题)。


另一种可能性是您希望此 rank 从 0 开始,然后在每次向列表中添加新项目时递增它。那么:

this.state = {
  rank: 0,
  users
}

添加用户时,您需要在代码中的某个地方调用:

this.setState({ rank: this.state.rank + 1 })

排序有什么问题?假设您有一个名为 'Sort by score' 的按钮,当您单击它时,它应该执行如下操作:

_sortByScore() {
  this.setState({ 
    users: this.state.users.slice().sort((a, b) => a.score - b.score) 
  })
}

这里要小心,如果你不调用类似 slice 的东西,排序会直接改变你的状态。