【发布时间】:2022-01-02 11:57:44
【问题描述】:
我有一个数组,它的值转换为按钮。单击每个按钮时,其值将写入 ul 列表中。当点击“Pop”时,最后一个值被删除。
预期输出:
我使用 useStack 钩子来实现它。但是运行后,输出是一个空白页,我在控制台收到这个错误:
Uncaught TypeError: stack is undefined
components.js:
import React from 'react';
import {useStack} from './hooks'
export function Demo() {
return (
<div className="demo">
<StackDemo/>
</div>
);
}
const words = ['Apple', 'Banana', 'Cherry', 'Grape'];
function StackDemo() {
const {stack, push, pop} = useStack();
return (<div>
{words.map((word, index) => <button key={index} onClick={() => push(word)}>{word}</button>)}
<button onClick={pop}>» Pop</button>
<ul>
{stack.map((item, index) => <li key={index}>{item}</li>)}
</ul>
</div>);
}
hooks.js:
import {useState} from 'react';
export function useStack() {
const [array,setArray] = useState([]);
const add = (value) => {
return setArray(array.push(value));
}
const del = () => {
return setArray(array.pop());
}
return {array, add, del};
}
当然,如果我编辑 components.js:
// const {stack, push, pop} = useStack(); to // 常量 [stack, push, pop] = useStack();
并编辑 hooks.js:
// return {array, add, del} to // return [array, add, del]
但是当我点击其中一个时,输出将变成空白页,并且我在控制台中收到此错误:
Uncaught TypeError: stack.map is not a function
有什么问题?我应该如何将 useStack 输出 分配给 const {stack, push, pop} ??
感谢您的帮助。
【问题讨论】:
-
您的
useStack返回一个带有键array、add和del的对象。您必须将它们以及函数(假设您继续使用对象简写)重命名为stack、push和pop,以便按照您的方式使用它。 -
PS 你的
add和del(或push和pop,如果你将它们重命名为)不会像我想的那样工作。但这是一个不同的问题。 -
@RobinZigmond 为什么名称应该相同?我做到了,现在页面变成空白并给了我:(stack.map 不是函数)
-
啊,这个新错误是因为我在第二条评论中提到的问题
-
至于为什么名称应该相同,我不明白这个问题。如果
useStack返回一个对象,其唯一的键是array、add和del,你为什么期望它有一个stack属性而不是undefined?
标签: javascript reactjs react-hooks