[英]How to make like function in React Native?
Code代码
Detail.js细节.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.在这段代码中, this.state.liked
是 false 并且 onPress 改变了它的状态。
When coming back to this page, this.state.linked
returns to false.返回此页面时, this.state.linked
返回 false。
What I want to do is I wanna keep state
in this class the latest.我想要做的就是我想保持state
在这个类中的最新产品。
So, I want to keep this.state.liked : true
when I come back to this page until I change its' state.所以,当我回到这个页面时,我想保持this.state.liked : true
,直到我改变它的状态。
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
.基本上,当您离开页面时,该组件会unmounts
,这意味着它会与state
一起从 DOM 中删除。 (calling componentWillUnmount
before it disappears) (在它消失之前调用componentWillUnmount
)
As pointed out in the comment: solution could be something like Redux/MobX redux toolkit, etc.正如评论中指出的那样:解决方案可能是 Redux/MobX redux 工具包等。
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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.