【发布时间】:2019-08-22 02:11:00
【问题描述】:
我有一个可以工作的 React 类组件,我想将其转换为功能组件以使用钩子进行状态等。我正在学习 React 钩子。类组件版本运行良好,功能组件是我需要帮助的地方。
数据结构由一个包含三个“客户”的客户列表组成。它的图像在这里:
我要做的就是获取这些数据,对其进行迭代并向用户显示每个名称键的数据。很简单。
问题是从我的组件调用 firebase 会导致无法正确检索数据的不稳定行为。最后一个客户端名称被连续调用,它冻结了浏览器。 :)
这是结果的图像:
代码如下:
import React, {Component,useContext,useEffect, useState} from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import ListItem from '@material-ui/core/ListItem';
import Button from '@material-ui/core/Button';
import firebase from 'firebase/app';
import {Consumer,Context} from '../../PageComponents/Context';
const styles = theme => ({
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing.unit * 2,
textAlign: 'center',
color: theme.palette.text.secondary,
},
});
const FetchData = (props) =>{
const [state, setState] = useState(["hi there"]);
const userID = useContext(Context).userID;
useEffect(() => {
let clientsRef = firebase.database().ref('clients');
clientsRef.on('child_added', snapshot => {
const client = snapshot.val();
client.key = snapshot.key;
setState([...state, client])
});
});
//____________________________________________________BEGIN NOTE: I am emulating this code from my class component and trying to integrate it
// this.clientsRef.on('child_added', snapshot => {
// const client = snapshot.val();
// client.key = snapshot.key;
// this.setState({ clients: [...this.state.clients, client]})
// });
//___________________________________________________END NOTE
console.log(state)
return (
<ul>
{
state.map((val,index)=>{
return <a key={index} > <li>{val.name}</li> </a>
})
}
</ul>
)
}
FetchData.propTypes = {
classes: PropTypes.object.isRequired
}
export default withStyles(styles)(FetchData)
【问题讨论】:
标签: javascript reactjs firebase firebase-realtime-database react-hooks