更改已由cloneWithRows呈现的行中的数据

时间:2016-09-02 08:51:58

标签: reactjs react-native

我想实现像facebook这样的东西,比如'一些帖子上的功能,但是我不知道我应该做什么来改变数据源中的数据,并根据用户按下按钮,基本上是一个计数器重新渲染一个特定的行。 这是我的代码:

export default class PrivateFeedList extends Component {
 constructor(props) {
 super(props);
 var ds = new ListView.DataSource({
  rowHasChanged: (r1, r2) => r1 != r2
})
this.state = {
  datasource: ds.cloneWithRows( [] ),
  refreshing: false
}

componentWillMount() {
 this.fetchPrivateFeed()
}
_onRefresh() {
this.setState({refreshing: true});

this.fetchPrivateFeed()
    .then(() => {
      this.setState({refreshing: false});
    });
}

render() {
 return(
  <View style= {styles.container}>
    <ListView
      refreshControl={
        <RefreshControl
          refreshing={this.state.refreshing}
          onRefresh={this._onRefresh.bind(this)}
        />
      }
      dataSource={this.state.datasource}

      renderRow={this.renderRow.bind(this)}
      />
  </View>
  )
 }

fetchPrivateFeed() {
 fetch('http://000.111.22.333:3000/', {
  method: 'GET',
  headers: {
    'Authorization': 'id_token ' + token
  }
 })
  .then((response) => response.json())
    .then((feedItems) => {
      console.log(feedItems)
      this.setState({
        datasource: this.state.datasource.cloneWithRows(feedItems)
      });
     })
    }

renderRow(rowData) {
 return(
  <View style={styles.cardWrapper}>

   <Text>{rowData.numberOfLikes}</Text>

   {this.props.showLikeButton
       ? <Button onPress={()=> this.handleLikePress(rowData)}>
           {this.hasUserLiked(rowData)
              ? <Text>LIKED</Text>
              : <Text>LIKE!!</Text>
           }
         </Button>
       : null
    }
  </View>
 )
}

 hasUserLiked(transaction) {
  let result = false;
   //userLiked is an array that contains all the usernames that have 
    liked the transaction. We cycle through this array, to check if the 
    present user is within the array, meaning that he has already liked 
    the transaction.
   _.each(transaction.userLiked, function(userLikedItem) {
    //has the user liked ? true or false
   result = user.userName === userLikedItem;
   })

   return result;
 }

 handleLikePress(rowData) {
  //Increase the numberOfLikes counter

  //Push present user's username into the userLiked array.

  //Re-render row.
 }

我想在handleLikePress()的评论中写下我写的最后三件事。

1 个答案:

答案 0 :(得分:0)

您不会改变dataSource,而是再次使用新行填充dataSource

handleLikePress(rowData) {
//Increase the numberOfLikes counter

//Push present user's username into the userLiked array.


this.setState({dataSource: this.state.dataSource.cloneWithRows(
        newDataSource,
    )});
}