【发布时间】:2020-10-18 10:14:30
【问题描述】:
我整天都被困在这个问题上,希望能得到一些帮助。提前致谢。
一开始我是这样写的,但是我会得到一个类型错误:todos.map is not a function。
function toggleState() {
setTodos(state => ({ ...state, isComplete: !state.isComplete }))
}
最后我意识到错误是因为它正在将 todos 作为对象返回,所以我尝试了这个:
function toggleState() {
setKeywords(state => [{ ...state, isUsed: !state.isUsed }])
}
现在我没有收到类型错误,但它仍然没有按预期工作。这是toggleState之前的状态:
[
{
"name": "State",
"value": [
{
"todo": "Learn React",
"id": "91bad41d-1561-425a-9e77-960f731d058a",
"isComplete": false
}
]
这是之后的状态:
[
{
"name": "State",
"value": [
{
"0": {
"todo": "Learn React",
"id": "91bad41d-1561-425a-9e77-960f731d058a",
"isComplete": false
},
"isComplete": true
}
]
这是我的其余代码:
import React, { useState, useEffect } from 'react'
import { uuid } from 'uuidv4'
import { Form, FormGroup, Input, Button } from 'reactstrap'
function Example(props) {
const [todos, setTodos] = useState([])
// Run when component first renders
useEffect(() => {
console.log('useEffect component first rendered')
if (localStorage.getItem('todoData')) {
setTodos(JSON.parse(localStorage.getItem('todoData')))
}
}, [])
// Run when todos state changes
useEffect(() => {
console.log('useEffect todos changed')
localStorage.setItem('todoData', JSON.stringify(todos))
}, [todos])
const [formInput, setFormInput] = useState()
function handleChange(e) {
setFormInput(e.target.value)
}
function handleSubmit(e) {
e.preventDefault()
setTodos(prev => prev.concat({ todo: formInput, id: uuid(), isComplete: false }))
setFormInput('')
}
function toggleState() {
setTodos(state => [{ ...state, isComplete: !state.isComplete }])
}
return (
<div className='text-center'>
<div className='mb-2 border text-center' style={{ height: '300px', overflowY: 'scroll' }}>
{todos.map(todo => (
<p className={todo.isUsed ? 'text-success my-1' : 'text-danger my-1'} key={todo.id}>
{todo.todo}
</p>
))}
</div>
<Form onSubmit={handleSubmit}>
<FormGroup>
<Input onChange={handleChange} type='text' name='text' id='todoForm' placeholder='Enter a todo' value={formInput || ''} />
<Button>Set Todo</Button>
</FormGroup>
</Form>
<Button onClick={toggleState}>Toggle isComplete</Button>
</div>
)
}
export default Example
【问题讨论】:
-
在您的“Toggle isComplete”按钮中,您没有传递任何要切换 IsComplete 的 Todo 项的引用。您是否尝试为所有项目切换所有 IsComplete?
-
最终我想通过 ID 切换单个项目,但我试图让它先处理一个项目。
标签: javascript reactjs react-hooks react-state-management use-state