簡體   English   中英

React.FC 組件返回內部的效果

[英]Effect inside the return of a React.FC Component

我使用 React 創建了這個網站,但我遇到了以下問題:

I have a function that returns createElement creating a Card with the information of my store's products (#1) , for this to be displayed on the screen I make a map in the array that the backend returns to me by passing the createElement function (# 2(請參閱返回)) ,但是,我希望這個 map 發生在我的后端響應存儲更改的 State 更改時。

你能幫助我嗎?

代碼:

后端響應是一個JSON,接口如下

interface RendererData {
   id: string;
   name: string;
   price: number;
   description: string;
   image: string;
}

#1

const renderer = useCallback((dados: RendererData) => {
return React.createElement(StyledCard, { key: dados.id }, [
  <Card key={dados.id}>
    <Card.Img src={`http://localhost:3333/${dados.image}`} />
    <Card.Body>
      <Card.Title>{dados.name}</Card.Title>
      <Card.Text>R$ {dados.price}</Card.Text>
    </Card.Body>
    <Card.Footer>
      <input type="number" placeholder="Qtd." min="0" max="10" />
      <Button className="add-to-cart" variant="primary">
        ADICIONAR AO CARRINHO
        <FaCartPlus size={28} />
      </Button>
    </Card.Footer>
  </Card>,
]);
}, []);

#2

const GridProducts: React.FC = () => {
 const [test, setTest] = useState([]);


 useEffect(() => {
    async function getProducts() {
     api.get('/products').then(
      await function (response) {
       setTest(response.data);
       },
     );
    }
    getProducts();
  }, []);


 const renderer = useCallback((dados: RendererData) => {
   return React.createElement(StyledCard, { key: dados.id }, [
     <Card key={dados.id}>
       <Card.Img src={`http://localhost:3333/${dados.image}`} />
       <Card.Body>
         <Card.Title>{dados.name}</Card.Title>
         <Card.Text>R$ {dados.price}</Card.Text>
       </Card.Body>
       <Card.Footer>
         <input type="number" placeholder="Qtd." min="0" max="10" />
         <Button className="add-to-cart" variant="primary">
           ADICIONAR AO CARRINHO
           <FaCartPlus size={28} />
         </Button>
       </Card.Footer>
     </Card>,
   ]);
 }, []);

 return (
   <>
     <div style={{ display: 'flex', justifyContent: 'center' }}>
       <Container>{test.map(config => renderer(config))}</Container>
     </div>
   </>
 );
};

解決了!

我剛剛用 map 添加了一個回調:

const display = useCallback(() => {
  return test.map(config => renderer(config));
}, [test]);

並改變了回報:

<div style={{ display: 'flex', justifyContent: 'center' }}>
   <Container >{display()}</Container>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM