gpt4 book ai didi

javascript - 将 useEffect 与组件类一起使用

转载 作者:行者123 更新时间:2023-12-02 02:44:07 25 4
gpt4 key购买 nike

我有一个类用于呈现数据库中的用户列表

    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>

);
}
}

问题是这段代码会抛出以下错误:

Invalid Hook call, Hooks can be called only inside of the bodycomponent

我认为不可能在类组件内使用钩子(Hook)..如果不可能,从此类中的服务器获取数据的最佳方法是什么?

最佳答案

您不能在类组件中使用 Hook 。请改用 componentDidMount

关于javascript - 将 useEffect 与组件类一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63081558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com