更新评论列表以响应新的反馈发布。

huangapple go评论76阅读模式
英文:

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 &#39;@react-navigation/native&#39;;
import React, { useEffect, useState } from &#39;react&#39;;
import {
StyleSheet,
View,
Text,
Image,
ScrollView,
TouchableOpacity,
Modal,
TextInput,
Alert,
} from &#39;react-native&#39;;
import { Button, Paragraph, Wrapper } from &#39;../components&#39;;
import { baseStyle, images, theme, routes } from &#39;../config&#39;;
import axios from &#39;axios&#39;;
import { useContext } from &#39;react&#39;;
import { AuthContext } from &#39;../context/AuthContext&#39;;
export const Reviews = ({ route }) =&gt; {
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(&#39;&#39;);
const [text, setText] = useState(&#39;&#39;);
const [refresh, setRefresh] = useState(0);
const handleSubmit = async () =&gt; {
console.log(&#39;Submitted Feedback: &#39;, text);
if (text.trim() === &#39;&#39;){
Alert.alert(&#39;Error&#39;, &#39;Feeback cannot be blank&#39;);
}
else{
await axios.post(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`, {
feedback: text, token: userInfo.data
}).then(res =&gt; {
let FeedbackInfo = res.data;
// setFeedbackinfo(FeedbackInfo);
// AsyncStorage.setItem(&#39;FeedbackInfo&#39;, JSON.stringify(FeedbackInfo));
setRefresh(refresh+1);
console.log(FeedbackInfo);
Alert.alert(&#39;Success&#39;,FeedbackInfo.message);
}).catch(e =&gt; {
console.log(`feedback error ${e}`);
});
setisModalVisible(!isModalVisible);
}
}
React.useState(async () =&gt; {
await axios.get(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`)
.then(response =&gt; {
setResponseData(response.data.data);
})
.catch(error =&gt; {
console.log(error);
});
}, [refresh]);
return (
&lt;Wrapper&gt;
&lt;View style={styles.header} &gt;
&lt;TouchableOpacity onPress={() =&gt; navigation.goBack()}&gt;
&lt;Image source={images.back} style={styles.backIcon} /&gt;
&lt;/TouchableOpacity&gt;
&lt; Text style={styles.headerText} &gt; Reviews &lt;/Text&gt;
&lt;/View&gt;
&lt;ScrollView showsVerticalScrollIndicator={false} style={styles.review} &gt;
{console.log(responseData)}
{responseData &amp;&amp;
responseData.length &gt; 0
?
responseData.map((item) =&gt; (
&lt;View style={styles.reviewContainer}&gt;
&lt;View style={styles.flex} &gt;
&lt;Paragraph style={styles.reviewer} &gt; {item.name} &lt;/Paragraph&gt;
&lt;/View&gt;
&lt;Paragraph&gt;
{item.feedback_desc}
&lt;/Paragraph&gt;
&lt;/View&gt;
))
:
null
}
&lt;/ScrollView&gt;
&lt;View style={styles.footer} &gt;
&lt;TouchableOpacity&gt;
&lt;Button onPress={() =&gt; {
if (userInfo.data) setisModalVisible(true);
else navigation.navigate(routes.LOGIN, { item: item });
}}&gt; Post a review &lt;/Button&gt;
&lt;/TouchableOpacity&gt;
&lt;/View&gt;
&lt;Modal
transparent={true}
animationType=&#39;slide&#39;
visible={isModalVisible}
&gt;
&lt;View style={styles.modalContainer}&gt;
&lt;TextInput
label=&quot;Review&quot;
multiline={true}
//Capitalize=&quot;none&quot;
mode=&quot;outlined&quot;
activeOutlineColor={theme.colors.blue}
style={{ height: 40 }}
placeholder=&quot;Type here to enter a feedback&quot;
onChangeText={newText =&gt; setText(newText)}
value={text}
/&gt;
&lt;View style={{...styles.modalButtonContainer, width: &#39;70%&#39;}}&gt;
&lt;Button onPress={() =&gt; handleSubmit()}&gt; Submit &lt;/Button&gt;
&lt;Button onPress={() =&gt; setisModalVisible(false)}&gt; Close &lt;/Button&gt;
&lt;/View&gt;
&lt;/View&gt;
&lt;/Modal&gt;
&lt;/Wrapper &gt;
);
};

答案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]);

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

英文:

useState doesn't work like that - you may be thinking of useEffect.

        // original code
        React.useState(async () =&gt; {
            await axios.get(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`)
                .then(response =&gt; {
                    setResponseData(response.data.data);
                })
                .catch(error =&gt; {
                    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(() =&gt; {
            axios.get(`https://514c-119-157-87-212.ngrok-free.app/listing/${item.id}/feedback`)
                .then(response =&gt; {
                    setResponseData(response.data.data);
                })
                .catch(error =&gt; {
                    console.log(error);
                });
        }, [refresh]);

Here are the docs for useState and useEffect if you would like to read more about them.

huangapple
  • 本文由 发表于 2023年6月30日 00:36:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定