为什么这在类组件中不起作用,而在功能组件中起作用?
功能组件(工作)
export default function App() {
const initCols = [
{
name: 'name',
},
];
const [cols, setCols] = useState(initCols); // works
}
ClassComponent(不工作)
class testclass extends Component {
const initCols = [
{
name: "name"
}];
state = {cols: initCols} // donot work
}
你不能在类组件中定义const值因为它是一个类但你可以这样做:
state = {
cols: [
{
name: "name"
}
]
};
有什么理由必须把它放在const变量中吗?
你也可以在组件之前定义它,然后像这样使用:
const initCols = [
{
name: "name"
}];
class testclass extends Component {
state = {cols: initCols}
//可以了
const initCols = [
{
name: "name"
}];
class testclass extends Component {
state = {cols: initCols}
....