Javascript 在react native中将数据从子组件传递到父组件?
我正在使用我的应用程序中的组功能,我希望能够选择多个朋友,并在创建像whatsapp这样的组时将他们添加到一起 但我无法做到这一点。 在父组件的平面列表中呈现父组件(AddMembers)和子组件(AddMembersComp)。我面临的问题是我的createGroup()方法和一个members数组,每次在子组件中按下“Add”按钮,关联的userId就会被推送到members数组 但实际情况是,正在为每个子组件创建一个成员数组,按下“添加”按钮时,uid将被推送到与该特定组件关联的数组中 我想要实现的是,在按下每个子组件上的add按钮时,将uid推入一个通用数组,即与整个列表关联,而不是列表中的特定组件。然后最终运行forEach将数组推送到数据库 正在发生的问题的屏幕截图: 正如您所看到的,点击第一个添加按钮时,将创建一个新的成员数组并按下uid,但点击第二个添加按钮时,将创建另一个成员数组,并将uid推入该数组,而不是推入旧数组。 我怎样才能解决这个问题?? 请帮忙 这是我的代码:Javascript 在react native中将数据从子组件传递到父组件?,javascript,arrays,firebase,react-native,react-navigation,Javascript,Arrays,Firebase,React Native,React Navigation,我正在使用我的应用程序中的组功能,我希望能够选择多个朋友,并在创建像whatsapp这样的组时将他们添加到一起 但我无法做到这一点。 在父组件的平面列表中呈现父组件(AddMembers)和子组件(AddMembersComp)。我面临的问题是我的createGroup()方法和一个members数组,每次在子组件中按下“Add”按钮,关联的userId就会被推送到members数组 但实际情况是,正在为每个子组件创建一个成员数组,按下“添加”按钮时,uid将被推送到与该特定组件关联的数组中 我
//子组件-AddMembersComp
类AddMembersComp扩展组件{
建造师(道具){
超级(道具);
此.state={
文档ID:“”,
新增成员:[],
};
this.email=this.props.email;//从父级传递的道具
this.username=this.props.username;
this.uid=this.props.uid;
this.name=this.props.name;
this.desc=this.props.desc;//从父级传递的道具
this.members=[];//将UID推入此数组
}
async addMembers(){//按add按钮调用此函数
等待这个.members.push(this.uid);
}
createGroup(){
var docRef=firestore()
.集合(“组”)
.doc();
firestore()
.runTransaction(事务=>{
返回事务.get(docRef).then(doc=>{
this.setState({docId:doc.id});
事务.set(docRef{
姓名:this.name,
desc:this.desc,
createdOn:new Date(),
});
});
})
.然后(()=>{
log('this.members:',this.members);
this.setState({addedMembers:this.members});
log('state members:',this.state.addedMembers);
})
.然后(()=>{
this.state.addedMembers.forEach(成员=>{
firestore()
.集合(“组”)
.doc(`${this.state.docId}`)
.集合(“成员”)
.doc(`${member}`)
.设置({
角色:'参与者',
joinedOn:新日期(),
});
});
});
}
render(){
返回(
{this.uid}
{
this.addMembers()。然后(()=>
console.log('State members:',this.members),
);
}}
/>
);
}
}
//父组件-AddMembersScreen
类AddMembersScreen扩展组件{
建造师(道具){
超级(道具);
此.state={
朋友们:[],
friendsData:[],
};
this.tempFriends=[];
this.tempFriendsData=[];
console.log(“添加成员屏幕”);
this.name=this.props.navigation.getParam('name');
this.desc=this.props.navigation.getParam('desc');
}
componentDidMount(){
这个是fetchFriends()
.然后(()=>
这是我的国家({
朋友们:这是我的朋友们,
}),
)
.然后(()=>this.fetchEachFriend());
}
异步fetchFriends(){
const uid=auth().currentUser.uid;
等待firestore()
.收藏(‘友谊’)
.where('uid1','=',`${uid}`)
.get()
。然后(doc=>{
如果(单据为空){
无效的
console.log('DOC:',DOC.empty);
}否则{
doc.forEach(snap=>{
console.log(snap.data().uid2);
this.tempFriends.push(snap.data().uid2);
console.log(this.tempFriends);
});
}
})
.catch(err=>console.log('Error DOC1',err));
等待firestore()
.收藏(‘友谊’)
.where('uid2','=',`${uid}`)
.get()
。然后(doc=>{
如果(单据为空){
无效的
console.log('DOC2:',doc.empty);
}否则{
doc.forEach(snap=>{
console.log(snap.data().uid1);
this.tempFriends.push(snap.data().uid1);
console.log(this.tempFriends);
});
}
})
.catch(err=>console.log('Error DOC2',err));
}
fetchEachFriend(){//正在获取要显示的每个朋友的数据
this.state.friends.forEach(uid=>{
log('UID:',UID);
firestore()
.collection('用户')
.doc(`${uid}`)
.get()
。然后(doc=>{
console.log('Friend Data',doc.Data());
这个.tempFriendsData.push({
uid:doc.id,
数据:doc.data(),
});
})
.then(()=>this.setState({friendsData:this.tempFriendsData}))
.catch(错误=>{
log('Error fetchEachFriend():',err);
});
});
}
_renderItem=({item})=>(
);
render(){
返回(
index.toString()}
renderItem={this.\u renderItem}
/>
);
}
}
我想知道解决方案可能是这样的:
每次按下add按钮时,uid都会被发送到父组件,并被推送到一个通用成员数组中。但是我应该如何做到这一点呢???你需要处理“添加的”
// PARENT COMPONENT - AddMembersScreen
class AddMembersScreen extends Component {
constructor(props) {
super(props);
this.state = {
friends: [],
friendsData: [],
addedMembers: []
};
this.tempFriends = [];
this.tempFriendsData = [];
console.log('Add Members Screen');
this.name = this.props.navigation.getParam('name');
this.desc = this.props.navigation.getParam('desc');
}
componentDidMount() {
this.fetchFriends()
.then(() =>
this.setState({
friends: this.tempFriends,
}),
)
.then(() => this.fetchEachFriend());
}
async fetchFriends() {
const uid = auth().currentUser.uid;
await firestore()
.collection('Friendships')
.where('uid1', '==', `${uid}`)
.get()
.then(doc => {
if (doc.empty) {
null;
console.log('DOC: ', doc.empty);
} else {
doc.forEach(snap => {
console.log(snap.data().uid2);
this.tempFriends.push(snap.data().uid2);
console.log(this.tempFriends);
});
}
})
.catch(err => console.log('Error DOC1 ', err));
await firestore()
.collection('Friendships')
.where('uid2', '==', `${uid}`)
.get()
.then(doc => {
if (doc.empty) {
null;
console.log('DOC2: ', doc.empty);
} else {
doc.forEach(snap => {
console.log(snap.data().uid1);
this.tempFriends.push(snap.data().uid1);
console.log(this.tempFriends);
});
}
})
.catch(err => console.log('Error DOC2 ', err));
}
fetchEachFriend() { //Fetching each friends data to display
this.state.friends.forEach(uid => {
console.log('UID: ', uid);
firestore()
.collection('Users')
.doc(`${uid}`)
.get()
.then(doc => {
console.log('Friend Data ', doc.data());
this.tempFriendsData.push({
uid: doc.id,
data: doc.data(),
});
})
.then(() => this.setState({friendsData: this.tempFriendsData}))
.catch(err => {
console.log('Error fetchEachFriend(): ', err);
});
});
}
handleMemberPress = (intUid) => {
const { addedMembers } = this.state
this.setState({
addedMembers: [...addedMembers, intUid]
})
}
_renderItem = ({item}) => (
<View>
<AddMembersComp
onPress={this.handleMemberPress}
email={item.data.email}
username={item.data.username}
uid={item.uid}
name={this.name}
desc={this.desc}
/>
</View>
);
render() {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<FlatList
data={this.state.friendsData}
keyExtractor={(item, index) => index.toString()}
renderItem={this._renderItem}
/>
</View>
);
}
}
// CHILD COMPONENT - AddMembersComp
class AddMembersComp extends Component {
constructor(props) {
super(props);
this.state = {
docId: '',
addedMembers: [],
};
this.email = this.props.email; //Props passed from the parent
this.username = this.props.username;
this.uid = this.props.uid;
this.name = this.props.name;
this.desc = this.props.desc; //Props passed from the parent
this.members = []; //Pushing uids into this array
}
async addMembers() { //Calling this on pressing the add button
await this.members.push(this.uid);
}
createGroup() {
var docRef = firestore()
.collection('Groups')
.doc();
firestore()
.runTransaction(transaction => {
return transaction.get(docRef).then(doc => {
this.setState({docId: doc.id});
transaction.set(docRef, {
name: this.name,
desc: this.desc,
createdOn: new Date(),
});
});
})
.then(() => {
console.log('this.members: ', this.members);
this.setState({addedMembers: this.members});
console.log('state members: ', this.state.addedMembers);
})
.then(() => {
this.state.addedMembers.forEach(member => {
firestore()
.collection('Groups')
.doc(`${this.state.docId}`)
.collection('Members')
.doc(`${member}`)
.set({
role: 'participant',
joinedOn: new Date(),
});
});
});
}
handleOnPressMember = () => {
const { onPress } = this.props;
onPress(this.uid)
}
render() {
return (
<View>
<Text>{this.uid}</Text>
<Button
title="Add"
onPress={this.handleOnPressMember}
/>
</View>
);
}
}