React学习:函数组件中使用componentDidMount加载数据问题求助
代码错误排查&修复方案
核心问题1:生命周期钩子使用场景错误
componentDidMount 是类组件专属的生命周期方法,你当前编写的Home是函数组件,不能直接在函数组件内部以类方法的形式声明使用。
问题2:命名拼写错误
就算是在类组件中使用,你写的componentdidMount拼写也不规范,正确的驼峰命名为componentDidMount。
修复方案
函数组件要实现「组件挂载完成后执行逻辑」的需求,使用useEffect Hook,传入空数组作为依赖项时,其执行时机和类组件的componentDidMount完全一致。
修正后完整代码如下:
import React, { useEffect } from "react"; import {Card, Button, Container, Row, Col} from 'react-bootstrap'; import addquantity from '../Functions/quantityadd.js'; const numberOfCards = 100; const Home = (props) => { // 等价于类组件的componentDidMount useEffect(() => { console.log('First this called'); // 这里写加载商品列表的请求逻辑,拿到数据后可以配合useState存储渲染 }, []); return ( <div> <h2>Home</h2> <Container> <Row xs={3} md={4} lg={6}> {[...Array(numberOfCards)].map((e, i) => { return ( <Col className='mt-5' key={i+1}> <Card > {/* <Card.Img top width="100%" src="/images/companylogo.png" alt="Card image cap"/> */} <Card.Body> <Card.Title tag="h5">Test</Card.Title> <Card.Subtitle tag="h6" className="mb-2 text-muted">Card subtitle</Card.Subtitle> <Card.Text>Some quick example text to build on the card title and make up the bulk of the card's content.</Card.Text> <Button onClick={() =>addquantity(i+1)}>Button</Button> </Card.Body> </Card> </Col> ) })} </Row> </Container> </div> ); } export default Home;
如果后续需要渲染真实的商品列表,你可以配合useState存储接口返回的商品数据,替换当前写死生成100个卡片的逻辑即可。
内容的提问来源于stack exchange,提问作者NooB Gamer
相关产品推荐
相关产品推荐

