React useEffect 渲染无法正常工作

时间:2021-03-06 05:58:19

标签: javascript reactjs

伙计们,我有问题。

我有这个代码

import React, { useState, useEffect, useCallback } from 'react';
import Watch from '../components/watch/index';

const RenderWatches = () => {
const [watches, setWatches] = useState([]);
const url ='https://swiss-watches-e8910-default-rtdb.firebaseio.com';

const getWatches = async () => {
    const promise = await fetch(`${url}/watches.json`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    });

    const watches = await promise.json();

    setWatches(watches);
};

useEffect(() => {
    getWatches();
}, []);

const render = () => {
    console.log(watches)
    return watches.map((watch) => {
       return(
           <Watch key={watch._id} {...watch} />
       ) 
    })
};

return (
    <div>{render()}</div>
);

};

export default RenderWatches;

在我的页面中呈现手表,但代码似乎执行了不止一次

screenshot of errors and rendering

请帮忙。

我不知道该怎么办。

0 个答案:

没有答案