在渲染之前获取 useEffect 钩子中的数据 - React [英] Fetch data inside useEffect hook before rendering - React

查看:31
本文介绍了在渲染之前获取 useEffect 钩子中的数据 - React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个原型,用于在 React 中获取 Spotify 用户的播放列表数据.数据获取在 useEffect 钩子内完成并设置播放列表变量的状态.因此,我想呈现每个播放列表的名称.但是,似乎只有在渲染后才获取数据,从而导致问题,因为在渲染之前未设置状态,因此未定义播放列表变量.如何在继续使用 React 钩子的同时解决这个问题?我的代码如下.

import './App.css'从查询字符串"导入查询字符串import React, { useState, useEffect } from 'react'const App = () =>{const [userData, setUserData] = useState({})const [accesstoken, setAccesstoken] = useState('')const [播放列表,设置播放列表] = useState({})useEffect(() => {让解析 = queryString.parse(window.location.search)让 accesstoken = parsed.access_token如果(!访问令牌){返回}设置访问令牌(访问令牌)获取('https://api.spotify.com/v1/me',{标头:{'授权':'承载'+访问令牌}}).then(response => response.json()).then(data => setUserData(data))获取(`https://api.spotify.com/v1/me/playlists`,{标头:{'授权':'承载'+访问令牌}}).then(response => response.json()).then(data => setPlaylists(data))}, [])返回(<div>{访问令牌?(<div><h1>欢迎您,{userData.display_name}</h1><h2>播放列表</h2><div>{playlists.items.map(playlist =><p>{播放列表名称}</p>)}

) : (<button onClick={() =>window.location = 'http://localhost:8888/login'}>登录)}

);}导出默认应用程序;

解决方案

使用条件渲染.检查渲染中的值

 

{用户数据&&<h1>欢迎,{userData.display_name}</h1>}<h2>播放列表</h2>{播放列表&&playlists.items &&(<div>{playlists.items.map((playlist) => (<p>{playlist.name}</p>))}

)}

;

I'm building a prototype that fetches a Spotify user's playlist data in React. The data fetching is done inside a useEffect hook and sets the state of playlists variable. Consequently, I want to render the name of each playlist. However, it seems that the data is only fetched after rendering, causing an issue, because the state is not set before rendering, so playlists variable is undefined. How can I solve this problem while continuing to use React hooks? My code is below.

import './App.css'
import queryString from 'query-string'
import React, { useState, useEffect } from 'react'

const App = () => {

  const [userData, setUserData] = useState({})
  const [accesstoken, setAccesstoken] = useState('')
  const [playlists, setPlaylists] = useState({})

  useEffect(() => {

    let parsed = queryString.parse(window.location.search)
    let accesstoken = parsed.access_token
    if (!accesstoken) {
      return
    }
    setAccesstoken(accesstoken)

    fetch('https://api.spotify.com/v1/me', {
      headers: {'Authorization': 'Bearer ' + accesstoken}
    }).then(response => response.json())
    .then(data => setUserData(data))

    fetch(`https://api.spotify.com/v1/me/playlists`, {
      headers: {'Authorization': 'Bearer ' + accesstoken}
    }).then(response => response.json())
    .then(data => setPlaylists(data))

  }, [])

  return(
    <div>
      {accesstoken ? (
        <div>
          <h1>Welcome, {userData.display_name}</h1>
          <h2>Playlists</h2>
          <div>
            {playlists.items.map(playlist => 
              <p>
                {playlist.name}
              </p>
            )}
          </div>
        </div>
      ) : (
        <button onClick={() => window.location = 'http://localhost:8888/login'}>Login</button>
      )}
    </div>
  );
}

export default App;

解决方案

Use conditional rendering. Check for values in render

   <div>
      {userData && <h1>Welcome, {userData.display_name}</h1>}
      <h2>Playlists</h2>
      {playlists && playlists.items && (
        <div>
          {playlists.items.map((playlist) => (
            <p>{playlist.name}</p>
          ))}
        </div>
      )}
    </div>;

这篇关于在渲染之前获取 useEffect 钩子中的数据 - React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆