javascript - 将 useEffect 与类组件一起使用
问题描述
我有一个类用于呈现数据库中的用户列表
export default class Users extends React.Component {
constructor() {
super()
this.state = {
data : [] //define a state
}
}
renderUsers = () => {
useEffect(() => {
fetch('exemple.com')
.then((response) => response.json())
.then((json) => this.setState({data: json.result})) // set returned values into the data state
.catch((error) => console.error(error))
}, []);
return this.state.data.map((value,key)=>{ // map state and return some views
......
})
}
render() {
return (
<View style={{ flex: 1 }}>
{this.renderUsers()} //render results
</View>
);
}
}
问题是这段代码会抛出以下错误:
Hook 调用无效,Hooks 只能在 body 组件内部调用
我认为不可能在类组件中使用钩子。如果不可能从此类内部的服务器获取数据的最佳方法是什么?
解决方案
您不能在类组件中使用挂钩。改为使用componentDidMount
。
推荐阅读
- ionic-framework - 当我使用 ionic cordova run android 时出现问题
- html - 为什么我的个人资料没有显示在相同的位置?
- python - 如何为大型数据集提高 django bulk_create 的性能?(PostgreSQL)
- php - 即使包含 SMTP.php,PHPMailer 也不发送邮件
- php - Wocomerce - 更新产品变化的最大数量
- alamofire - 使用 Alamofire 5 上传时访问 encodingResult
- docker - 在 Dockerfile 中实现我自己的 CMD 时是否可以不覆盖基本映像 CMD?
- c - 我可以在没有返回键“n”的情况下读取字符吗?(C)
- json - 将 JSON 文件导入 MS Access 表
- azure - 通过 Azure AD Graph API 作为电子邮件别名发送电子邮件