亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 useEffect 與類組件一起使用

將 useEffect 與類組件一起使用

交互式愛情 2022-12-02 11:22:35
我有一個用于從數據庫中呈現用戶列表的類    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 組件內部調用我認為不可能在類組件內部使用掛鉤。如果不可能,從此類內部的服務器獲取數據的最佳方法是什么?
查看完整描述

2 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

您不能在類組件中使用掛鉤。改用componentDidMount。



查看完整回答
反對 回復 2022-12-02
?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

鉤子只能用在功能組件中。


您可以將您的組件重寫為功能性組件,如下所示:


export default Users = () => {

    const [data, setData] = useState([]);


    useEffect(() => {

        fetch('exemple.com')

            .then((response) => response.json())

            .then((json) => setData(json.result)) // set returned values into the data state

            .catch((error) => console.error(error))

    }, []);


    const renderUsers = () => {

        return data.map((value, key) => {

            // DO STUFF HERE

        })

    }


    return (

        <View style={{ flex: 1 }}>

            {renderUsers()} //render results

        </View>

    )


}


查看完整回答
反對 回復 2022-12-02
  • 2 回答
  • 0 關注
  • 252 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號