React Native 当发布新的反馈时,我如何更新评论列表

isr3a4wc  于 2023-06-30  发布在  React
关注(0)|答案(1)|浏览(107)

当我发布新的反馈时,我正在尝试更新评论列表。我尝试添加一个useState,并在执行POST API的反馈时更新其状态。但由于没有观察到变化,因此没有取得成果。我仍然需要来回导航才能看到变化。我的代码中缺少什么?有人建议我使用Pusher,有些人甚至建议这是不可能的等等。

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 >
    );
};
soat7uwm

soat7uwm1#

useState并不是这样工作的--你可能会想到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]);

上面的代码会将你的异步函数存储在state中,返回一个state和setter的数组。但是,this的返回值不会被使用,所以它只会运行你的代码一次,不会再影响任何东西。
useState不接受第二个参数(依赖数组),因此不会使用它。
用useEffect重写它看起来像这样:

// 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]);

这里是useStateuseEffect的文档,如果你想了解更多关于它们的信息。

相关问题