希望你今天过得愉快
我试图基于Array类创建一个Grid数据结构,我打算添加自定义方法和属性,因此我从一个简单的Test类开始:
import { useState } from 'react'
class Grid extends Array {
constructor(data) {
console.log('called with', arguments);
super(...data)
}
}
function App() {
const [ count ] = useState(new Grid([1,2,3]))
return (
<div className="App">
{count.map(row => <p key={row.rowId}>
row {row}
</p>)}
</div>
)
}
export default App
我的最终目标是封装类中的所有逻辑,但当我将其导入应用程序时,它开始崩溃:
以下是我从chrome控制台获得的日志:
App.jsx:5 called with Arguments [Array(3), callee: (...), Symbol(Symbol.iterator): ƒ]
App.jsx:5 called with Arguments [3, callee: (...), Symbol(Symbol.iterator): ƒ]
App.jsx:5 called with Arguments [Array(3), callee: (...), Symbol(Symbol.iterator): ƒ]
App.jsx:5 called with Arguments [3, callee: (...), Symbol(Symbol.iterator): ƒ]
App.jsx:6 Uncaught TypeError: Found non-callable @@iterator
at new Grid (App.jsx:6:5)
at Grid.map (<anonymous>)
at App (App.jsx:15:14)
at renderWithHooks (react-dom.development.js:14985:18)
at mountIndeterminateComponent (react-dom.development.js:17811:13)
at beginWork (react-dom.development.js:19049:16)
at HTMLUnknownElement.callCallback2 (react-dom.development.js:3945:14)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:16)
at invokeGuardedCallback (react-dom.development.js:4056:31)
at beginWork$1 (react-dom.development.js:23964:7)
如您所见,构造函数多次被调用,有时使用提供的数组的最后一项.这是一些反应相关的行为吗?
发布于 2022-10-23 19:08:33
创建新网格时移除构造函数和方括号
import { useState } from 'react'
class Grid extends Array {}
function App() {
const [ count ] = useState(new Grid(1,2,3))
}
export default App
https://stackoverflow.com/questions/74176290
复制相似问题