我在iOS本机开发方面有经验,现在我正在尝试在react-native上构建我的第一个应用程序。
当我从波纹管数据库接收数据时,我正在尝试setSate:
state = {
remainingSeconds: 5,
dataArray: [],
};
componentDidMount() {
// Get data from firebase
this.getData();
}
getData() {
// Set the configuration for your app
var config = {
apiKey: "XXXXXX",
authDomain: "XXXXXXX",
databaseURL: "XXXXXXX",
storageBucket: ""
};
firebase.initializeApp(config);
// Get a reference to the database service
var database = firebase.database();
// Get data
var usersRef = firebase.database().ref('Users');
usersRef.on('value', function(snapshot) {
this.setState({
dataArray: snapshot.val()
})
});
};
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
有人可以帮忙吗?
在此先感谢您。
Looks like the issue is that your callback function where you call setState does not have the same context as it's parent function.
All you need to do to fix this is convert the callback function from the standard function declaration to an arrow function.
// Get data
var usersRef = firebase.database().ref('Users');
usersRef.on('value', (snapshot) => {
this.setState({
dataArray: snapshot.val()
})
});
Run Code Online (Sandbox Code Playgroud)
That should give you the right context so that this means the same thing in the callback function as in the parent function.
| 归档时间: |
|
| 查看次数: |
1681 次 |
| 最近记录: |