首页 > 解决方案 > 在本机反应中增加值

问题描述

我从有效载荷中获取数据,该有效载荷在每个帖子上都有点赞总数。在用户屏幕上,有一个用户喜欢帖子的图标,我想要实现的是当用户点击它时,显示的值会增加到针对该特定帖子的加 1

看法:

{
  posts.map((item, i) => {
    return (
      <View key={i} style={styles.user}>
        <Card>

          <ListItem
            titleStyle={{ color: '#36c', fontWeight:'500' }}
            titleNumberOfLines={2}
            hideChevron={false}
            roundAvatar
            title={item.headline}
            avatar={{uri:'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg'}}
          />

          <Text style={{marginBottom: 10, fontSize:16, color:'#4a4a4a', fontFamily:'HelveticaNeue-Light'}}>
            {item.text}
          </Text>

          <TouchableOpacity style={styles.likeContainer}>
            <Text style={{fontSize:14}}>{item.likesCount}{"\n"}</Text>
            <Icon
              onPress={()=>onLikePost(item)}
              name='md-thumbs-up'
              type='ionicon'
              iconStyle={[(item.isLiked=== true) ? styles.likedColor : styles.unLikedColor]}
            />
          </TouchableOpacity>
        </Card>
      </View>
    );
  })
}

容器:

state = {
  posts : [],
  id: '',
  user: ''
}

componentDidMount = () => {
  const { navigation } = this.props;
  this.setState({
    id : navigation.getParam('id'), 
    user: navigation.getParam('user')
  }, ()=> this.getData())
}

getData = () => {
  const api = create({
    baseURL: 'https://url.com/api',
    headers: {'Accept': 'application/json'}
  });
  api.get('/groups/'+`${this.state.groupID}`+'/posts').then((response) => {
    let data = response.data.data
    this.setState({ posts: data });
    console.log(JSON.stringify(this.state.posts))
  })
}

onLikePost = (item) => {
  item.likeCount = item.likeCount+1
}

标签: reactjsreact-native

解决方案


您正在将帖子数据存储在状态变量中,因此请使用setState它来更新它。使用map并检查每个帖子,只要 id(每个帖子的唯一属性)与单击项目的 id 匹配,则增加其 likesCount 否则返回相同的数据。

像这样写:

onLikePost = (item) => {
  this.setState(prevState => ({
    posts: prevState.posts.map(el => el.id === item.id? {...el, likesCount: el.likesCount+1} : el)
  }))
}

更新:在更新计数值之前进行检查并更改 isLiked bool

onLikePost = (item) => {
  this.setState(prevState => ({
    posts: prevState.posts.map(el => {
      if(el.id === item.id) {
        return {
          ...el,
          isLiked: !el.isLiked,
          likesCount: !el.isLiked? el.likesCount+1 : el.likesCount-1,
        }
      }
      return el;
    })
  }))
}

注意:我假设每个帖子都有一个键id唯一值,如果它不存在,则使用每个帖子的任何其他唯一属性。


推荐阅读