【发布时间】:2019-01-23 11:43:24
【问题描述】:
我正在尝试通过添加 + 1 来更新项目,而不让 fetch 更新项目。基本上,当我fetch 时,后端将数字更新为 + 1,而不是那样做,我想通过前端来做。
<TouchableOpacity
onPress={() => this.anim_like(item)} <-- Passing all items from dataSource
style={{position:'absolute', height: '100%', width: '100%', right: 140, bottom: 50}}
>
<Animation
progress={item.progress}
source={require('../Animations/favourite_app_icon.json')}
style={{ height: '100%', width: '100%', position: 'absolute'}}
resizeMode={`contain`}
/>
</TouchableOpacity>
<Text>{item.likes}</Text> <-- Getting likes from the fetched data
anim_like = (item) => {
Animated.timing(item.progress, {
toValue: 1,
duration: 1500,
easing: Easing.linear,
}).start();
fetch(`https://www.example.com/React/user-like.php`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
post_id : item.id,
})
}).then((response) => response.json())
.then((responseJson) => {
//this.refetchData(); <-- Current way to update item.likes
item.likes = item.likes + 1;<-- Want to update it this way by + 1 without updating the full fetch data
}).catch((error) => {
});
}
当然,anim_like 一旦点击,就会在后端添加 + 1。我目前拥有的方式是,一旦它在后端更新,重新获取结果并显示它。这会导致响应时间变慢。
这里是获取 api:
fetch(`https://www.example.com/React/user.php` , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
user_image: responseJson[0].user_images.map(item => ({ ...item, progress: new Animated.Value(0)})) <-- This adds a unique animated.value to each user
},function() {
});
})
.catch((error) => {
//console.error(error);
});
我使用this.state.user_image 从后端检索所有现有数据并将其放入renderItem 中的Flatlist。我显示我想要的数据,例如上面的代码,item.likes 或item.progress。
它还负责将其转换为 JSON 数组并使用 React Native 中的数据:
[{
"food":"pizza",
"who":"Person",
"user_images":[{
"id":"114",
"username":"Hannah_L123",
"images":"resized_1522-20131219-creativity.jpg",
"date":"12\/04\/2017",
"likes": "20"
}]
}]
如果其中有任何令人困惑的地方,我很乐意为它提供一些启示!谢谢!
【问题讨论】:
-
所以基本上你想在得到后端响应之前加1?
-
@bwalshy 好吧,加 1 而没有得到后端的响应。相反,前端将显示该响应,这应该消除调用另一个 fetch 的额外步骤。
-
听起来你可以在重新获取之前增加你的状态,当你得到重新获取的响应时,你可以检查它是否与前端显示的数字相对应。
-
@LaneyWilliams 我认为来自后端的帖子散文应该返回最后一个计数,这样您就可以从后端返回的数据中设置新状态而无需获取类似内容
-
您的代码中的
refetchData()在哪里?你能用它更新你的问题吗?
标签: json reactjs react-native fetch jsx