gpt4 book ai didi

javascript - 当前 React JS : 'state' is not defined no-undef

转载 作者:行者123 更新时间:2023-11-30 07:49:18 25 4
gpt4 key购买 nike

我正在学习 ReactJS,我遇到了这个错误 “状态”未定义 no-undef您对哪里出了问题的帮助。我有当前的 React“react”:“^16.8.6”。我尝试添加 this.state 而不是我得到:第 1 行:'Component' 已定义但从未使用过 no-unused-vars第 8 行:不要直接改变状态。使用 setState() react/no-direct-mutation-state

App.js

import React, { Component } from 'react';
import './App.css';
import Todos from './Components/Todos';



function App() {
state = {
todos:[
{
id:1,
title: "Study File Structure",
completed:false
},
{
id:2,
title: "Create Component",
completed:false
},
{
id:3,
title: "Study State",
completed:false
}
]
}

return (
<div className="App">

<h1>Hello</h1>
<Todos/>
</div>
);
}

export default App;

最佳答案

function App() { 替换为 class App extends Component{。这将使您朝着正确的方向前进,并将返回包装在渲染方法中,如下所示:

class App extends Component{
state = {
todos:[
{
id:1,
title: "Study File Structure",
completed:false
},
{
id:2,
title: "Create Component",
completed:false
},
{
id:3,
title: "Study State",
completed:false
}
]
}

render(){
return (
<div className="App">

<h1>Hello</h1>
<Todos/>
</div>
);
}
}

export default App;

关于javascript - 当前 React JS : 'state' is not defined no-undef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56226857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com