获取 setState 不是使用 React 钩子定义的 no-undef 错误



我刚刚开始使用 React。所以我用npx create-react-app .生成了一个新的 React 应用程序,它为我生成了一个我认为是功能性的 React 钩子组件。我想这是 2020 年的版本。

但是当我尝试更新我的状态时,我遇到了一个问题。我基本上想切换所选待办事项的completed属性。但是当我调用setTodos方法时,它给了我这个错误:

index.js:1 ./src/App.js 第 27:5 行:"setTodos"未定义 no-undef

import React, { useState } from 'react'
import Todos from './components/Todos.js'
function App()
{
const [todos, setTodos] = useState([
{ id: 1, title: 'First todo item', completed: false },
{ id: 2, title: 'Second todo item', completed: true },
{ id: 3, title: 'Third todo item', completed: false },
])
return (
<div>
<Todos
todos={todos}
markComplete={ (event, todo) => markComplete(event, todo) }
/>
</div>
)
}
function markComplete(event, todo)
{
// this works
console.log('You clicked todo with id: ' + todo.id + ' and title: ' + todo.title)
// setTodos is not defined...?
setTodos({
id: 1,
title: 'Test',
completed: true,
})
}
export default App

setTodos仅在定义它的函数(在本例中为App组件(的范围内。将markComplete移动到组件中。

import React, { useState } from 'react'
import Todos from './components/Todos.js'
function App() {
const [todos, setTodos] = useState([
{ id: 1, title: 'First todo item', completed: false },
{ id: 2, title: 'Second todo item', completed: true },
{ id: 3, title: 'Third todo item', completed: false },
]);
function markComplete(event, todo) {
console.log('You clicked todo with id: ' + todo.id + ' and title: ' + todo.title)
setTodos({
id: 1,
title: 'Test',
completed: true,
})
}
return (
<div>
<Todos
todos={todos}
markComplete={ (event, todo) => markComplete(event, todo) }
/>
</div>
)
}
export default App

markComplete放在与setTodos相同的函数作用域中

import React, { useState } from 'react'
import Todos from './components/Todos.js'
function App()
{
function markComplete(event, todo)
{
setTodos({
id: 1,
title: 'Test',
completed: true,
})
}
const [todos, setTodos] = useState([
{ id: 1, title: 'First todo item', completed: false },
{ id: 2, title: 'Second todo item', completed: true },
{ id: 3, title: 'Third todo item', completed: false },
])
return (
<div>
<Todos
todos={todos}
markComplete={ (event, todo) => markComplete(event, todo) }
/>
</div>
)
}
export default App

状态

  • 仅在组件内部使用状态。
  • 状态更改组件中的值。

因此,您必须将功能标记完成放在组件应用程序中

import React, { useState } from 'react'
import Todos from './components/Todos.js'
function App()
{
const [todos, setTodos] = useState([
{ id: 1, title: 'First todo item', completed: false },
{ id: 2, title: 'Second todo item', completed: true },
{ id: 3, title: 'Third todo item', completed: false },
])
const markComplete = (event, todo) =>
{
setTodos({
id: 1,
title: 'Test',
completed: true,
})
}
return (
<div>
<Todos
todos={todos}
markComplete={ (event, todo) => markComplete(event, todo) }
/>
</div>
)
}
export default App

相关内容

  • 没有找到相关文章

最新更新