【发布时间】:2021-06-21 08:20:36
【问题描述】:
我在将状态放入数组索引时遇到问题。
这里有一行错误:{WorkData[state].title}
我需要做的是显示 WorkData 的元素,它是一个包含对象的数组:标题、内容、img 数学等...
const WorkData = [
{
id: 0,
title: 'title',
subtext: 'React/Express',
content: 'content',
imgPath: 'imgPath',
},
{
id: 1,
title: 'Little Hero Academy',
subtext: 'React/API REST',
content:
'content,
imgPath: 'imgPath',
},
{
id: 2,
title: 'title',
subtext: 'subtext',
content: 'content',
imgPath: 'imgPath',
},
首先,我有一个卡片列表,其中包含一个包含数据的按钮:
<div className="work-container flex">
<div className="work-bloc zoom">
<div className="work-hover" />
<div className="work-text">
<div className="text-title">{WorkData[0].title}</div>
<span className="subtext">{WorkData[0].subtext}</span>
</div>
<div
onClick={togglePopup}
data-id={WorkData[0].id}
className="work-showmore button2"
>
Show More
</div>
</div>
</div>
我用这个函数将数据存储在状态:
const [id, setId] = useState();
const togglePopup = (e) => {
setIsOpen(!isOpen);
setId(e.target.dataset.id);
};
我需要这些数据才能到达弹出窗口,
<Popup
togglePopup={togglePopup}
closePopup={closePopup}
isOpen={isOpen}
id={id}
/>
我将状态传递给我的弹出组件并尝试显示所显示的 id 的值 另外,我需要弹出显示属于我在状态中传递的id(索引)的数组内容:workData 1 2 3 etc...
const Popup = ({ closePopup, isOpen, id }) => {
return (
<div className={`popup-container ${isOpen ? 'opened' : 'closed'}`}>
<div className={`popup ${isOpen ? 'opened2' : 'closed2'}`}>
<span className='popup-title'>
{WorkData[id].title}
{id}
</span>
<div className='image-container'>
<img
src='https://i.picsum.photos/id/1060/536/354.jpg?blur=2&hmac=0zJLs1ar00sBbW5Ahd_4zA6pgZqCVavwuHToO6VtcYY'
alt=''
/>
</div>
<p>
Team projet with React and API REST. Our goal was to make an app with
a choosen API and make something out of it. We did a superhero-themed
website with games for children.
<br />
Check on <AiFillGithub className='menuicon' />
</p>
<div onClick={closePopup} className='close-icon button2'>
Show less{' '}
</div>
</div>
</div>
);
};
但我收到此错误:
**TypeError: _WorkData__WEBPACK_IMPORTED_MODULE_1__.default[id] is undefined**
提前感谢您的任何建议
【问题讨论】:
-
可能还值得包括一个更完整的示例,这些 sn-ps 单独很有用,但它们不能让我们看到整个数据流,这在调试未定义时通常需要变量。
-
共享状态初始化。
-
@JuniusL。我用更多代码、状态和完整的弹出组件更新了我的帖子,告诉我它是否有帮助。如果您愿意,我也可以在 Gist 上发布完整代码
-
试试
const [id, setId] = useState(0);
标签: javascript reactjs state