javascript - 在 React 中的函数内更新类的状态
问题描述
我正在尝试使用存储在变量中的对象数组来更新此类的状态childData
。但是,当我使用setState({childData: childData)}
,并稍后通过调用使用它时this.state.childData
,它是undefined
,因此它永远不会使用信息更新状态。
class Users extends React.Component {
state = {
childData: ""
}
retrieve = () => {
let childData;
var leadsRef = database.ref('users');
leadsRef.on('value', function(snapshot) {
childData = snapshot.val();
console.log(childData)
this.setState({
childData: childData
})
});
}
componentDidMount() {
this.retrieve()
}
render() {
return(
<div>
<h3>These are all the users in the app</h3>
{console.log(this.state.childData)}
</div>
)
}
}
export default Users
解决方案
你有几个问题正在发生。首先,您确实需要在回调函数中设置状态。但是,照原样,您会遇到无限循环。那是因为您不应该在render
方法中执行异步功能。相反,请在componentDidMount
方法中执行此操作,以便仅在组件安装时触发。
class Users extends React.Component {
state = {
childData: ""
}
retrieve = () => {
let childData;
var leadsRef = database.ref('users');
leadsRef.on('value', snapshot => {
childData = snapshot.val();
console.log(childData)
this.setState({
childData: childData
})
});
}
componentDidMount() {
this.retrieve()
}
render() {
return(
<div>
<h3>These are all the users in the app</h3>
{console.log(this.state.childData)}
</div>
)
}
}
export default Users
推荐阅读
- python-asyncio - 相当于 Python 的“async def”函数中的“yield”
- google-cloud-firestore - Firestore 规则模拟器是否考虑了现有文档的实际集合?
- android - 使用动态变化的字段序列化传入的 JSON
- python - 如何打乱隐式对数组?
- storage - Openstack Hypervisor 本地存储增加大小
- regex - 逐行读取文件并替换字符串,打印到文件
- javascript - 从数据库加载时无法解析 ace 编辑器中的 javascript 标签
- apache-spark - 如何在 OLP 中覆盖 spark conf
- http - Gradle HTTP 插件
- python - 基于另一个数据框编辑数据框