所以我正在构建一个我想要实现的应用程序基本上是'喜欢'按钮打开,我似乎无法获得正确的组合以使其工作。基本上我想按一个像按钮,页面上有一个数字,显示它被喜欢的次数。有人有主意吗?这就是我到目前为止所做的:
import React from 'react';
import { StyleSheet,View, Image,TouchableOpacity,Text, StatusBar,
ScrollView } from 'react-native';
export default class SingleVeg extends React.Component {
constructor(props){
super(props)
console.log("Here", props);
this.state = {
data: {},
count: 0
}
this.update = this.update.bind(this)
}
update() {
this.setState({ count: this.state.data.count + 1 })
}
async componentDidMount() {
const response = await fetch(`https://just-
ripe.herokuapp.com/vegetable/$
{this.props.navigation.state.params.id}`)
const json = await response.json()
this.setState({data: json})
}
render(){
console.log(typeof this.state.data, this.state.data.id)
return (
<View style={styles.container}>
<View style={styles.image}>
<Image
style ={{ width: 350, height: 200
}}
source={require("../../images/JustRipe.png")}/>
</View>
<Text style={styles.title}>{this.state.data.title}</Text>
<TouchableOpacity style={styles.love} onPress ={this.update}>
<Text style= {styles.loveText}>Love: {this.state.data.count}</Text>
</TouchableOpacity>
&#13;
答案 0 :(得分:1)
您的更新功能中存在错误,应该是:
update() {
this.setState({ count: this.state.count + 1 })
}
VS。 this.state.data.count
您还应该将文本更新为从计数中读取。即
Love: {this.state.count}
当你保存状态时:
this.setState({data: json, count: json.count})
答案 1 :(得分:0)
这里的问题是你有2 count
存储。
删除状态中的count
:
this.state = {
data: {},
count: 0
}
并更新数据中的正确计数:
this.setState({ data: { ...data, count: this.state.data.count + 1 }})
答案 2 :(得分:0)
import React from 'react'`enter code here`;
class Counter extends React.Component {
state = { count: 0 }
increment = () => {
this.setState({
count: this.state.count + 1
});
}
decrement = () => {
this.setState({
count: this.state.count - 1
});
}
render() {
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement}>-</button>
<span>{this.state.count}</span>
<button onClick={this.increment}>+</button>
</div>
</div>
)
}
}
export default Counter;