gpt4 book ai didi

javascript - useContext 给出错误无法读取未定义的属性 '...'

转载 作者:行者123 更新时间:2023-12-04 04:18:18 26 4
gpt4 key购买 nike

我需要有关此问题的帮助,我的应用程序组件如下图所示。我要存储轨道对象inselectedTrack在使用 useState 的状态下当我单击查看详细信息按钮时。然后使用它来显示轨道详细信息,而不是从 API 再次获取以获取大头钉详细信息,但是当我使用 useContext里面给我这个错误TypeError: Cannot read property 'selectedTrack' of undefined .
React Components

import React from 'react';
import Header from './Header';
import Search from '../tracks/Search';
import Tracks from '../tracks/Tracks';
import Footer from './Footer';
import TrackContextProvider from '../../contexts/TrackContext';

const Main = () => {
return (
<div>
<TrackContextProvider>
<Header />
<Search />
<Tracks />
<Footer />
</TrackContextProvider>
</div>
);
};

export default Main;

TrackContext.js
import React, { createContext, useState, useEffect } from 'react';
export const TrackContext = createContext();

const TrackContextProvider = props => {

const [tracks, setTracks] = useState([]);
const [selectedTrack, setSelectedTrack] = useState([{}]);

const API_KEY = process.env.REACT_APP_MUSICXMATCH_KEY;

useEffect(() => {
fetch(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=10&country=fr&f_has_lyrics=1&apikey=${API_KEY}`
)
.then(response => response.json())
.then(data => setTracks(data.message.body.track_list))
.catch(err => console.log(err));
// to disable the warning rule of missing dependency
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

// state for heading
const [heading, setHeading] = useState(['Top 10 Tracks']);

return (
<TrackContext.Provider value={{ tracks, heading, selectedTrack, setSelectedTrack }}>
{props.children}
</TrackContext.Provider>
);
};

export default TrackContextProvider;
import React, { Fragment, useContext } from 'react';
import { Link } from 'react-router-dom';
import { TrackContext } from '../../contexts/TrackContext';

const TrackDetails = () => {
const { selectedTrack } = useContext(TrackContext);
console.log(selectedTrack);
return (
<Fragment>
<Link to="/">
<button>Go Back</button>
</Link>
<div>
{selectedTrack === undefined ? (
<p>loading ...</p>
) : (
<h3>
{selectedTrack.track.track_name} by {selectedTrack.track.artist_name}
</h3>
)}
<p>lyrics.............</p>
<div>Album Id: </div>)
</div>
</Fragment>
);
};

export default TrackDetails;
import React, { useState, useContext, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { TrackContext } from '../../contexts/TrackContext';

const Track = ({ trackInfo }) => {
const { selectedTrack, setSelectedTrack } = useContext(TrackContext);

const handleClick = e => {
setSelectedTrack(trackInfo);
};

console.log(selectedTrack);

return (
<li>
<div>{trackInfo.track.artist_name}</div>
<div>Track: {trackInfo.track.track_name}</div>
<div>Album:{trackInfo.track.album_name}</div>
<div>Rating:{trackInfo.track.track_rating}</div>
<Link to={{ pathname: `/trackdetails/${trackInfo.track.track_id}`, param1: selectedTrack }}>
<button onClick={handleClick}>> View Lyric</button>
</Link>
</li>
);
};

export default Track;

更新:添加轨道组件
import React, { useContext, Fragment } from 'react';
import Track from './Track';
import { TrackContext } from '../../contexts/TrackContext';

const Tracks = () => {
const { heading, tracks } = useContext(TrackContext);

const tracksList = tracks.map(trackInfo => {
return <Track trackInfo={trackInfo} key={trackInfo.track.track_id} />;
});
return (
<Fragment>
<p>{heading}</p>
{tracks.length ? <ul>{tracksList}</ul> : <p>loading...</p>}
</Fragment>
);
};

export default Tracks;

最佳答案

我认为这里的问题是因为 selectedTrack异步加载,当从上下文访问时,它是未定义的(您可以通过在 TrackContext 调用中传入默认值来绕过 undefinedcreateContext)。由于 selectedTrack 变量是随时填充的,因此您应该将其存储在 Ref 中。与 useRef钩子(Hook),并将该 ref 作为上下文值的一部分返回。这样您将获得 selectedTrack 的最新值来自该上下文的任何消费者。


const selectedTracks = useRef([]);
useEffect(() => {
fetch(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=10&country=fr&f_has_lyrics=1&apikey=${API_KEY}`
)
.then(response => response.json())
.then(data => {
selectedTrack.current = data.message.body.track_list;
})
.catch(err => console.log(err));
// to disable the warning rule of missing dependency
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

关于javascript - useContext 给出错误无法读取未定义的属性 '...',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60082621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com