在userlist.js中代码看起来像
const renderItems = ({item}) => {
if (item !== undefined) {
const user = {
image:'https://www.w3schools.com/w3images/avatar6.png',
name: item.name,
lastMessage: item.lastChat,
time: item.latest_timestamp,
seen: item.seen,
id: item._id,
};
if(item._id!==userID)return <DocList user={user} nav={nav} sendToParents={fn} from="userlist"/>;
else return null;
}
return null;
};
const DATA = [
{
data: friends,
},
];
return (
<View style={{marginTop:53,marginBottom:130}}>
{friends.length==0?
<View style={{alignSelf:'center',marginTop:90}}>
<Image style={{resizeMode:'stretch',width:350,height:220,alignSelf:'center'}} source={require('../../asserts/No_chats.png')} />
<Text style={{textAlign:'center',fontWeight:'bold',marginTop:10,color:'#838383'}}>No recent chats !</Text>
<Text style={{textAlign:'center',textAlign:'center',width:300,alignSelf:'center',color:'gray'}}>Not yet started conversation? press the green + icon to see the list of users you can chat with.</Text>
</View>
:
<SectionList
sections={DATA}
keyExtractor={(item, index) => index.toString()}
renderItem={renderItems}
renderSectionHeader={({section: {title}}) => (
<View>{title}</View>
)}>
</SectionList> }
</View>
);
};
在newuser.js里面看起来像
const handleRender = ({ item }) => {
const user = {
image: 'https://www.w3schools.com/w3images/avatar6.png',
name: item.name,
lastMessage: item.lastChat,
time: item.latest_timestamp,
seen: item.seen,
id: item._id,
};
return (
<DocList user={user} nav={nav} sendToParents={handleCallback} from="newuser" />
);
};
return (
<View>
<FlatList
data={docs}
keyExtractor={(item, index) => index.toString()}
renderItem={handleRender}
/>
</View>
);
};
DocList组件是:
import {socketSubsribe, socketIdentity, socketUnsubscribe} from './SocketServer';
import axios from 'axios';
import {StyleSheet, Text, View, Image, TouchableOpacity} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {BASE_URL, BASE_URL1} from '../../Components/Urls';
import { nowTime } from '../../Components/Clock';
import socket from "../components/SocketServer";
const DocList = ({user, nav, sendToParents,from}) => {
const [latestmsg,setLatestmsg]=useState(user.lastMessage);
const [userImg,setUserImg]=useState(null);
const [seen,setSeen]=useState(user.seen);
const [roomID,setRoomID]=useState();
let latmsg;
// const textBold = user.seen ? 'normal' : 'bold';
const textBold ='bold';
const subscribe=async()=>{
//await AsyncStorage.removeItem("chatUsers");
const resultRoomidChat= await AsyncStorage.getItem(`${user.id}`);
if(resultRoomidChat){
const {roomId,chat}=JSON.parse(resultRoomidChat);
console.log(roomId,"ROOMId");
setRoomID(roomId);
}
const { userId,userToken} = JSON.parse(
await AsyncStorage.getItem('userToken')
);
const GET_IMAGE_URL=BASE_URL1+"/api/user/getUserImg";
const resultUser= await axios.get(GET_IMAGE_URL+`/${user.id}`,{
headers:{
authorization:`Bearer ${userToken}`
}
});
//console.log("RESULTUSER",resultUser.data.picture,typeof(resultUser.data.picture));
if(resultUser.data.picture){
// console.log("USER Image",resultUser.data.picture);
let imgsrc=resultUser.data.picture;
setUserImg(imgsrc);
//console.log("IMGSRC",imgsrc);
}
socketIdentity(userId);
//console.log("SUNSCRIBE IDENTITY");
const object =await AsyncStorage.getItem(`${user.id}`);
if(object){
//console.log("SUNSCRIBE OTHERUSER");
const {roomId}=JSON.parse(object);
socketSubsribe(roomId, user.id);
}
}
const handleRequest = async () => {
try {
const {userToken, userId} = JSON.parse(
await AsyncStorage.getItem('userToken'),
);
const URL= BASE_URL+'/api/chat/initiate';
const data={
userIds: [userId, user.id],
type: 'customer-to-doctor',
}
console.log("1",URL, data);
const res= await axios.post(URL,data,{
headers:{
authorization:`Bearer ${userToken}`
}
})
console.log("2",res.data,res.status);
if (res.data && res.status ) {
const {chatRoom} = res.data;
const id = chatRoom.chatRoomId;
console.log("CHATROOM ID iS",id)
const object1=await AsyncStorage.getItem(`${user.id}`);
console.log("object1 ",object1);
if(object1){
const object=JSON.parse(object1);
const modifiedObject={
roomId:id,
medium:'app',
chat:[...object.chat]
}
await AsyncStorage.setItem(`${user.id}`, JSON.stringify(modifiedObject));
console.log("USER.ID",user.id,modifiedObject);
}else{
await AsyncStorage.setItem(`${user.id}`, JSON.stringify({roomId: id,medium:'app', chat:[]}));console.log("after setting ROOM ID");
}
}
} catch (e) {
console.log(e, '==>> error in app doclist');
}
};
const call2doclist=async(msg,postedByUser,seen)=>{
try{
const {userInfo} = JSON.parse(
await AsyncStorage.getItem('chatUsers'),
);
const {userId} = JSON.parse(
await AsyncStorage.getItem('userToken'),
);
//console.log("uI in DOCLIST");
if(userInfo){
console.log("hi call2doclist");
let i=0;
for(i=0;i<userInfo.length;i++){
if(userInfo[i]._id==user.id){
//console.log("hi3");
console.log("POSTEDBYVUSER CHECK",postedByUser,userId,user.id);
if(seen==true && postedByUser==userId){
console.log('hi4');
userInfo[i].seen=true;
setSeen(true);
}else{
userInfo[i].seen=false;
setSeen(false);
}
userInfo[i].lastChat=msg;
setLatestmsg(msg);
console.log("userInfo[i]",userInfo[i],seen);
break;
}
}
await AsyncStorage.setItem(
'chatUsers',
JSON.stringify({userInfo:[...userInfo]}),
);
}
user.lastMessage=msg;
setLatestmsg(user.lastMessage);
console.log("SEEN",seen);
}catch(e){
console.log("Error in call2 inside doclist",e)
}
}
const handlePress = async () => {
setLatestmsg('');
console.log(latestmsg,from);
await handleRequest();
if(from=="newuser"){
sendToParents(user.id);
}
console.log("inside doclist",user);
console.log("hey");
nav.navigate('ChatSc', {name: user.name, id: user.id ,from:'app',call2doclist:{call2doclist}});
};
const updateChat=async(msg)=>{
try{
const data = JSON.parse(await AsyncStorage.getItem(`${user.id}`));
await AsyncStorage.removeItem(
`${user.id}`
);
data.chat.unshift({
side:msg.side,
text:msg.text,
message_id:msg.message_id,
time: msg.time,
});
//console.log("i saev");
await AsyncStorage.setItem(
`${user.id}`,
JSON.stringify({...data}),
);
}catch(e){
console.log("Error in updating chats",e);
}
}
const update2=async(msg)=>{
await updateChat(msg)
}
socket.off('new message'+`${roomID}`).on('new message'+`${roomID}`,(data,err)=>{
try{
if(err){ console.log("error in socket recieving",err)}
if(!err){
console.log("inside DOCLIST for app");
const msg={
// postedByUser:data.message.postedByUser._id,
message_id:data.message.postId,
side:user.id === data.message.postedByUser._id ? 'left':'right',
text:data.message.message.messageText,
time:data.message.message.time,
timestamp:nowTime()
};
update2(msg);
call2doclist(data.message.message.messageText,data.message.postedByUser._id,false);
}
}catch(e){
console.log(e,"Error in chatScreen of inside doclist ",e.message)
}
});
const subscribe2=async()=>{
await subscribe();
console.log("hi");
}
useEffect(()=>{
subscribe2();
},[]);
return (
<TouchableOpacity onPress={()=>handlePress()}>
<View style={styles.topContainer}>
{/* user Image */}
<View style={{...styles.ImageContainer}}>
<Image source={{uri:userImg?userImg:user.image}} style={{...styles.imageStyle}} />
</View>
{/* user data value */}
<View style={styles.userContainer}>
<View style={styles.userInfo}>
<View>
<Text>{user.name}</Text>
<Text style={{fontWeight: textBold,paddingRight:30}}>{seen==false?latestmsg:''}</Text>
</View>
<View>
</View>
</View>
</View>
</View>
</TouchableOpacity>
);
};
export default DocList;
const styles = StyleSheet.create({
imageStyle: {
width: 70,
height: 70,
borderRadius: 70,
},
topContainer: {
paddingLeft:10,
flexDirection: 'row',
width: '100%',
height: 78,
marginTop: 10,
marginBottom: 10,
paddingTop: 0,
},
ImageContainer: {
width: 70,
alignItems: 'flex-end',
},
userContainer: {
flex: 1,
marginLeft: 5,
justifyContent: 'space-around',
},
userInfo: {
flexDirection: 'row',
justifyContent: 'space-between',
padding: 5,
},
});
通过userlist.js console.log打印2,响应数据和状态,但通过newuser它不打印这些东西,尽管它打印1,URL,数据。这意味着有一些问题本身,但在前一种情况下,它击中API和日志在后端,但在后一种情况下,它不击中,不记录任何东西在后端。
检查item参数是否正确传递给newuser.js中的handleRender函数。也检查在控制台的网络选项卡是否它实际上击中API或由于身份验证问题,调用必须被拒绝。