Change the state of particular component individually in flatlist as in facebook like btns

廉价感情. 提交于 2019-12-13 02:26:56

问题


I've a lists of like icons in a flatlist. I want to change the color if the particular icon is clicked. But if I use likeStatus state to do it and click any icon, then the color of all the icons will change. How can I treat individual icon separately in flatlist using state? I've tried a lot but in vain. Any help is appreciated. Thanks in advance

constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      likeStatus: null,
    };
}

componentDidMount() {
    this._reload();
}

_reload = () => {
    return fetch(url)
      .then(response => response.json())
      .then(responseJson => {
        this.setState({
          isLoading: false,
          data: responseJson.data
        });
      })
      .catch(error => {
        console.log(error);
    });
 };

likePost = item => {
    this.setState({
      likeStatus: !item.like_status
    });
    if (this.state.likeStatus == true) {
      ToastAndroid.show(`You have unliked the post`, ToastAndroid.SHORT);
    } else {
      ToastAndroid.show(`You have liked the post`, ToastAndroid.SHORT);
    }
    fetch(likeUploadUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        post_id: item.id,
        user_id: item.user_id
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        console.log("likeResponse", responseJson);
      })
      .catch(error => {

      });
  };

_renderItem = item => {
    return (
        _ _ _ _ _ _ _ _ _ _
        _ _ _ _ _ _ _ _ _ _

        <TouchableOpacity
          activeOpacity={0.5}
          onPress={() => this.likePost(item.item)}
          style={{ flexDirection: "row" }} >
              {item.item.like_status != null &&
              item.item.like_status != false ? (
                <FontAwesome5
                  name={"heart"}
                  size={15}
                  style={{color: "blue" }}
                />
              ) : (
                <FontAwesome5
                  name={"heart"}
                  size={15}
                  style={{ color: "gray" }}
                />
              )}
        </TouchableOpacity>
    );
  };

render() {
    return(
        <FlatList
            data={this.state.data}
            renderItem={this._renderItem}
         />
    );
}

回答1:


There are many solutions to this problem but my suggestion is this

In your main .js file change render like this.

render() {
   return(
      <FlatList
        data={this.state.data}
        renderItem={(item) => <MyItem item={item}/>}
      />
  );

}

//in MyItem.js
export default class MyItem extends React.Component {
    constructor(props){
        super(props);
        this.state={
            like_status: false;
        };
    }

    likePost = item => {
    this.setState({
      like_status: !this.state.like_status
    });
    if (this.state.likeStatus == true) {
      ToastAndroid.show(`You have unliked the post`, ToastAndroid.SHORT);
    } else {
      ToastAndroid.show(`You have liked the post`, ToastAndroid.SHORT);
    }
    fetch(likeUploadUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        post_id: item.id,
        user_id: item.user_id
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        console.log("likeResponse", responseJson);
      })
      .catch(error => {

      });
    };

    render(){
        return (
        _ _ _ _ _ _ _ _ _ _
        _ _ _ _ _ _ _ _ _ _

        <TouchableOpacity
          activeOpacity={0.5}
          onPress={() => this.likePost(this.props.item.item)}
          style={{ flexDirection: "row" }} >
              {this.state.like_status != null &&
              this.state.like_status != false ? (
                <FontAwesome5
                  name={"heart"}
                  size={15}
                  style={{color: "blue" }}
                />
              ) : (
                <FontAwesome5
                  name={"heart"}
                  size={15}
                  style={{ color: "gray" }}
                />
              )}
        </TouchableOpacity>
);
}
}

This is a clean way to do this. Just render your FlatList items in another class so that you can have a separate state for each item.



来源:https://stackoverflow.com/questions/52023541/change-the-state-of-particular-component-individually-in-flatlist-as-in-facebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!