简体   繁体   中英

How to make like function in React Native?

Code

Detail.js

constructor(props) {
  super(props);
  this.state = {
    liked = false
  };
}

export default class Detail extends React.Component {
 render() {
  const { liked } = this.state;
  return (
   ...
   <TouchableOpacity
     onPress{() => 
       this.setState({ 
         liked: !liked,
       });
     } 
   >
    ...
   </TouchableOpacity>
   ...
  )
}

In this code, this.state.liked is false at first and onPress changes its state.

When coming back to this page, this.state.linked returns to false.

What I want to do is I wanna keep state in this class the latest.

So, I want to keep this.state.liked : true when I come back to this page until I change its' state.

If you want the data to be stored it the app, when you navigate back and forth, then you need to use a common storage.

Basically when you navigate away from the page, this component unmounts , which means it's erased from the DOM along with it's state . (calling componentWillUnmount before it disappears)

As pointed out in the comment: solution could be something like Redux/MobX redux toolkit, etc.

You can even implement your own storage if you like, but this could get tricky if your project grow.

also a note on your constructor, change:

this.state = {
    liked = false // << liked: false
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM