0

我正在构建一个以 Supabase 作为后端的 React 应用程序。我想在 React 中显示我的几个 supabase 表中的内容。但是,我承诺会提取这些数据,但我不确定如何在 React 中显示它。下面是我的代码:

SupaBase API Call: 

    async function getData() {
      const {data, other} = await getWriters().then(
        function(response) {
          for (var i = 0; i < response.length; i++) {
            var writerInfo = {}
            writerInfo['username'] = response[i].username
            writerInfo['bio'] = response[i].bio
            // console.log('Writer Name: ', response[i].username);
            // console.log('Writer Bio: ', response[i].bio);
            getTagIds(response[i].writerId).then(
              function(response2) {
                for (var j = 0; j < response2.length; j++) {
                  getTagNames(response2[j].tag_id).then(
                    function(response3) {
                      writerInfo['categories'] = []
                      // console.log('Categories: ')
                      for (var k = 0; k < response3.length; k++) {
                        // console.log(response3[k].tag_name)
                        writerInfo['categories'] = response3[k].tag_name
                      }
                    }
                  )
                }
              }
            )
          }
          return writerInfo['username']
        }
      )
      return data
    }

反应代码:

export default function BrowsePage() {
  const classes = useStyles();
  const [listOfWriters, setListOfWriters] = useState({});

  const fetchData = async () => {
      setListOfWriters(getWriters())
    }


    console.log(getData())

  return (
    <Grid container spacing={3}>
      <Grid item sm={12}>
      <Navbar />
      </Grid>
      <Grid item xs={12} className={classes.root}>
      {getData}
      
      </Grid>
      <Grid item sm={12}>
      <Footer />
      </Grid>
    </Grid>
  );
}
4

1 回答 1

1
  1. 我创建了一个名为useWriteListthis is just another function 的自定义钩子。查看此原始文档

  2. useEffect仅在其任何依赖项数组更改时调用提供的回调函数。

在这种情况下,只在组件第一次渲染时立即调用,因为它是一个空数组。

所以你可以把它想象成一个像we will call this callback function whenever blabla changes.

由于它只是一个声明,它不会阻止渲染流程。

  1. 在回调内部,我们等待数据并设置listOfWriters最终将导致重新渲染。
    const useWriterList = () => {
      const [listOfWriters, setListOfWriters] = useState([]);
      useEffect(async () => {
        try {
          setListOfWriters(await getData());
        } catch (e) {}
      }, []);
      return listOfWriters;
    };
    
    export default function BrowsePage() {
      //...
      const listOfWriters = useWriterList();
    
      return (
        <Grid container spacing={3}>
          //...
          {listOfWriters.map(writer => (
            <div>
              {writer.name}
            </div>
          ))}
          //...
        </Grid>
      );
    }
于 2021-06-07T01:52:07.770 回答