我有一个数组,它的值转换为按钮。单击每个按钮时,它的值将写入ul列表中。当单击“Pop”时,最后一个值是remove。
预期输出:
我使用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 {堆栈,push,pop} = useStack();到 // const 堆栈,push,pop = useStack();
并编辑hooks.js:
//返回{,add,del}到//返回数组,add,del
然后显示输出:
但是,当我单击其中之一时,输出将变成空白页,并在控制台中接收到此错误:
Uncaught TypeError: stack.map is not a function
有什么问题吗?如何将useStack输出分配给const {堆栈、push、pop}?
谢谢你的帮助。
发布于 2022-01-02 12:26:45
useStack
钩子有几个问题:
add
函数:const add = (value) => {
return setArray(array.push(value));
}
array.push
returns a number (新数组的长度),而不是添加新元素后的数组。这会导致白页(由JavaScript TypeError
引起,因为现在stack
不再是数组了)。
为了解决这个问题,我建议:
const add = (value) => {
return setArray(array.concat(value));
}
del
函数:const del = () => {
return setArray(array.pop());
}
在本例中,刚刚弹出的array.pop
returns the value,所以现在堆栈是一个字符串而不是数组。
为了解决这个问题,我建议:
const del = () => {
return setArray(array.slice(1));
}
下面是一个有用的示例:https://codesandbox.io/s/brave-neumann-41ltx?file=/src/App.js。
https://stackoverflow.com/questions/70555751
复制相似问题