英文:
How do I update the review list when a new feedback is posted
问题
// 导入所需模块和库
import { useNavigation } from '@react-navigation/native';
import React, { useEffect, useState, useContext } from 'react';
import {
StyleSheet,
View,
Text,
Image,
ScrollView,
TouchableOpacity,
Modal,
TextInput,
Alert,
} from 'react-native';
import { Button, Paragraph, Wrapper } from '../components';
import { baseStyle, images, theme, routes } from '../config';
import axios from 'axios';
import { AuthContext } from '../context/AuthContext';
// Reviews 组件
export const Reviews = ({ route }) => {
// 使用 useContext 获取用户信息
const { userInfo } = useContext(AuthContext);
// 使用 useNavigation 获取导航功能
const navigation = useNavigation();
// 状态变量的初始化和更新
const [isModalVisible, setisModalVisible] = useState(false);
const { item } = route.params;
const [responseData, setResponseData] = useState();
const [inputText, setInputText] = useState('');
const [text, setText] = useState('');
const [refresh, setRefresh] = useState(0);
// 处理提交反馈的函数
const handleSubmit = async () => {
console.log('提交的反馈内容: ', text);
if (text.trim() === '') {
Alert.alert('错误', '反馈内容不能为空');
}
else {
await axios.post(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`, {
feedback: text, token: userInfo.data
}).then(res => {
let FeedbackInfo = res.data;
setRefresh(refresh + 1);
console.log(FeedbackInfo);
Alert.alert('成功', FeedbackInfo.message);
}).catch(e => {
console.log(`反馈错误 ${e}`);
});
setisModalVisible(!isModalVisible);
}
}
// 组件加载时获取反馈信息
useEffect(async () => {
await axios.get(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`)
.then(response => {
setResponseData(response.data.data);
})
.catch(error => {
console.log(error);
});
}, [refresh]);
// 返回 JSX 元素
return (
<Wrapper>
<View style={styles.header}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<Image source={images.back} style={styles.backIcon} />
</TouchableOpacity>
<Text style={styles.headerText}>评论</Text>
</View>
<ScrollView showsVerticalScrollIndicator={false} style={styles.review}>
{console.log(responseData)}
{responseData &&
responseData.length > 0
?
responseData.map((item) => (
<View style={styles.reviewContainer}>
<View style={styles.flex}>
<Paragraph style={styles.reviewer}>{item.name}</Paragraph>
</View>
<Paragraph>
{item.feedback_desc}
</Paragraph>
</View>
))
:
null
}
</ScrollView>
<View style={styles.footer}>
<TouchableOpacity>
<Button onPress={() => {
if (userInfo.data) setisModalVisible(true);
else navigation.navigate(routes.LOGIN, { item: item });
}}>发表评论</Button>
</TouchableOpacity>
</View>
<Modal
transparent={true}
animationType='slide'
visible={isModalVisible}
>
<View style={styles.modalContainer}>
<TextInput
label="评论"
multiline={true}
mode="outlined"
activeOutlineColor={theme.colors.blue}
style={{ height: 40 }}
placeholder="在此输入反馈内容"
onChangeText={newText => setText(newText)}
value={text}
/>
<View style={{ ...styles.modalButtonContainer, width: '70%' }}>
<Button onPress={() => handleSubmit()}>提交</Button>
<Button onPress={() => setisModalVisible(false)}>关闭</Button>
</View>
</View>
</Modal>
</Wrapper>
);
};
英文:
I am trying to update the review list when I post a new feedback. I tried adding a useState
and updates its state when ever POST API of feedback is executed. but it was not fruitful since no changes were observed. I still have to navigate back and forth to see the changes. What am I lacking in my code? Someone suggested me to use Pusher and some even suggested it is not possible etc.
import { useNavigation } from '@react-navigation/native';
import React, { useEffect, useState } from 'react';
import {
StyleSheet,
View,
Text,
Image,
ScrollView,
TouchableOpacity,
Modal,
TextInput,
Alert,
} from 'react-native';
import { Button, Paragraph, Wrapper } from '../components';
import { baseStyle, images, theme, routes } from '../config';
import axios from 'axios';
import { useContext } from 'react';
import { AuthContext } from '../context/AuthContext';
export const Reviews = ({ route }) => {
const { userInfo } = useContext(AuthContext);
const navigation = useNavigation();
const [isModalVisible, setisModalVisible] = useState(false);
const { item } = route.params;
const [responseData, setResponseData] = React.useState();
const [inputText, setInputText] = useState('');
const [text, setText] = useState('');
const [refresh, setRefresh] = useState(0);
const handleSubmit = async () => {
console.log('Submitted Feedback: ', text);
if (text.trim() === ''){
Alert.alert('Error', 'Feeback cannot be blank');
}
else{
await axios.post(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`, {
feedback: text, token: userInfo.data
}).then(res => {
let FeedbackInfo = res.data;
// setFeedbackinfo(FeedbackInfo);
// AsyncStorage.setItem('FeedbackInfo', JSON.stringify(FeedbackInfo));
setRefresh(refresh+1);
console.log(FeedbackInfo);
Alert.alert('Success',FeedbackInfo.message);
}).catch(e => {
console.log(`feedback error ${e}`);
});
setisModalVisible(!isModalVisible);
}
}
React.useState(async () => {
await axios.get(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`)
.then(response => {
setResponseData(response.data.data);
})
.catch(error => {
console.log(error);
});
}, [refresh]);
return (
<Wrapper>
<View style={styles.header} >
<TouchableOpacity onPress={() => navigation.goBack()}>
<Image source={images.back} style={styles.backIcon} />
</TouchableOpacity>
< Text style={styles.headerText} > Reviews </Text>
</View>
<ScrollView showsVerticalScrollIndicator={false} style={styles.review} >
{console.log(responseData)}
{responseData &&
responseData.length > 0
?
responseData.map((item) => (
<View style={styles.reviewContainer}>
<View style={styles.flex} >
<Paragraph style={styles.reviewer} > {item.name} </Paragraph>
</View>
<Paragraph>
{item.feedback_desc}
</Paragraph>
</View>
))
:
null
}
</ScrollView>
<View style={styles.footer} >
<TouchableOpacity>
<Button onPress={() => {
if (userInfo.data) setisModalVisible(true);
else navigation.navigate(routes.LOGIN, { item: item });
}}> Post a review </Button>
</TouchableOpacity>
</View>
<Modal
transparent={true}
animationType='slide'
visible={isModalVisible}
>
<View style={styles.modalContainer}>
<TextInput
label="Review"
multiline={true}
//Capitalize="none"
mode="outlined"
activeOutlineColor={theme.colors.blue}
style={{ height: 40 }}
placeholder="Type here to enter a feedback"
onChangeText={newText => setText(newText)}
value={text}
/>
<View style={{...styles.modalButtonContainer, width: '70%'}}>
<Button onPress={() => handleSubmit()}> Submit </Button>
<Button onPress={() => setisModalVisible(false)}> Close </Button>
</View>
</View>
</Modal>
</Wrapper >
);
};
答案1
得分: 1
useState
不是这样使用的 - 你可能在想 useEffect
。
原始代码如下:
// 原始代码
React.useState(async () => {
await axios.get(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`)
.then(response => {
setResponseData(response.data.data);
})
.catch(error => {
console.log(error);
});
}, [refresh]);
上面的代码会将你的异步函数存储在状态中,返回一个状态数组和设置器。然而,这个返回值不会被使用,所以它只会运行你的代码一次,然后不会再产生任何影响。
useState
不接受第二个参数(依赖数组),所以它不会被使用。
使用 useEffect
重写会像这样:
// 无需混合使用 async/await 和 .then
React.useEffect(() => {
axios.get(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`)
.then(response => {
setResponseData(response.data.data);
})
.catch(error => {
console.log(error);
});
}, [refresh]);
如果你想了解更多关于它们的信息,这是 useState 和 useEffect 的文档链接。
英文:
useState
doesn't work like that - you may be thinking of useEffect.
// original code
React.useState(async () => {
await axios.get(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`)
.then(response => {
setResponseData(response.data.data);
})
.catch(error => {
console.log(error);
});
}, [refresh]);
The above code would store your async function in state, returning an array of the state and the setter. However the return value of this isn't used, so it would simply run your code once and never affect anything again.
useState doesn't take a second argument (the dependency array) so that won't be used.
Rewriting this with useEffect would look something like:
// no need to mix async/await and .then
React.useEffect(() => {
axios.get(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`)
.then(response => {
setResponseData(response.data.data);
})
.catch(error => {
console.log(error);
});
}, [refresh]);
Here are the docs for useState and useEffect if you would like to read more about them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论