首页 > 解决方案 > 将 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 组件内部调用

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

标签: javascriptreact-nativereact-native-androidreact-native-ios

解决方案


您不能在类组件中使用挂钩。改为使用componentDidMount


推荐阅读