我有一个类(User)异步提取数据,需要将它返回给我程序中的其他类。在React Native中执行此操作的最有效方法是什么。
user.js的
import firebase from 'firebase';
import { Component } from 'react';
class User extends Component {
constructor() {
super();
this.state = {
name: '',
email: '',
phone: '',
};
}
componentWillMount() {
const { currentUser } = firebase.auth();
return firebase.database().ref(`/users/students/${currentUser.uid}`)
.once('value')
.then((response) => {
this.setState({ name: response.val().displayName });
});
}
getName() {
return this.state.name;
}
}
export const getName = User.prototype.getName;
ActivityList.js
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import firebase from 'firebase';
import ActivityDetail from './ActivityDetail';
import { getName } from '../../models/User';
class ActivityList extends Component {
constructor() {
super();
this.state = { People: [] };
}
componentWillMount() {
return firebase.database().ref('/users/teachers/').once('value').then(response => this.setState({ People: response.val() }));
}
renderPeople() {
console.log('rendering');
return this.state.People.map(person => <ActivityDetail key={person.Name} person={person} />);
}
render() {
console.log(this.state);
console.log(getName().bind(this));
return (
<ScrollView>
{this.renderPeople()}
</ScrollView>
);
}
}
export { ActivityList };
答案 0 :(得分:0)
当你说:
console.log(getName().bind(this));
它只返回ActivityList :: state.name,它不存在。所以提出异常。
如果您需要,可以在user.js
中执行以下操作function getCurrentUser() {
const { currentUser } = firebase.auth();
return firebase.database().ref(`/users/students/${currentUser.uid}`)
.once('value')
.then((response) => {
return { name: response.val().displayName };
});
}
在其他课上只说:
getCurrentUser().then(currentUser => this.setState({name: currentUser.name});