gpt4 book ai didi

javascript - 使用 React hooks 获取 setState is not Define no-undef 错误

转载 作者:行者123 更新时间:2023-11-28 14:09:56 25 4
gpt4 key购买 nike

我刚刚开始使用 React。因此,我使用 npx create-react-app 生成了一个新的 React 应用程序。它生成了一个我认为功能性的 React hooks 组件。我猜这是 2020 版本。

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

index.js:1 ./src/App.js Line 27:5: 'setTodos' is not defined 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

关于javascript - 使用 React hooks 获取 setState is not Define no-undef 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59962162/

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