将 useEffect 与类组件一起使用

ane*_*hme 0 javascript react-native react-native-android react-native-ios

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

    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>
    
        );
      }
    }
Run Code Online (Sandbox Code Playgroud)

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

无效的 Hook 调用,只能在 body 组件内部调用 Hooks

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

Ste*_*ell 5

您不能在类组件中使用钩子。使用componentDidMount来代替。