reactjs - 为什么复选框不检查?(反应)
问题描述
我遇到奇怪的情况,我的 App 组件除了选中复选框外工作正常,而我在另一个项目中复制粘贴的同一个 App 组件工作正常。我再次创建了只有 App 组件的新项目,复制粘贴,同样的事情,除了复选框,一切都很好。谁能向我解释这里发生了什么?同一个组件怎么可能在一个项目中正常工作而在其他项目中却不行?我重新启动了一切。所以这是我的代码,只是一个简单的待办事项列表:
import React, { useRef, useReducer } from 'react'
function App() {
const inputRef = useRef<HTMLInputElement>(null)
const handleSubmit = (e: any) => {
e.preventDefault()
inputRef.current?.value !== "" && dispatch({ type: 'ADD_TODO', payload: inputRef.current?.value })
inputRef.current && (inputRef.current.value = "")
}
const [todo, dispatch] = useReducer((state: any, action: any): any => {
switch (action.type) {
case 'ADD_TODO':
return [...state, { id: state.length, name: action.payload, isCheck: false }]
case 'CHECK_TODO':
return state.filter((item: any, index: any):any => {
if (index === action.id) {
item.isCheck = !item.isCheck
}
return item
})
}
}, [])
const todos = todo.map((item: any, index: number) => {
return (
<li key={index}>
<input type="checkbox" checked={item.isCheck} onChange={() => dispatch({ type: "CHECK_TODO", id: index })} />
{item.name}
</li>
)
})
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Buy milk"
ref={inputRef}
/>
</form>
<ul>{todos}</ul>
</div>
)
}
export default App
在这里,在任何其他新项目中根本不起作用:
我没有做任何不寻常的事情,用npx create-react-app . --template typescript
编辑
这是单击复选框'eggs'时带有片段的控制台日志(不知道为什么它会渲染两次,在工作的项目中它只渲染一次):
case 'CHECK_TODO':
return state.filter((item: any, index: any): any => {
if (index === action.id) {
item.isCheck = !item.isCheck
console.log('click')
console.log(`${index} === ${action.id}`)
console.log(item.isCheck)
}
return item
})
解决方案
最后,找出了问题所在,所以事情是关于<React.StrictMode>
。唯一的区别是 index.js 在我的项目中运行良好
ReactDOM.render(<App />, document.getElementById('root'));
在其他我有
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
这也是组件渲染两次的原因。
所以删除<React.StrictMode>
标签是删除问题:)
推荐阅读
- c# - Unity中GameObject的引用脚本类
- php - 如何对数组值求和,数组是从 SQL 查询创建的
- swift - swift firebase 从存储中获取图像并在 JSQMessage 控制器中显示
- javascript - Google BigQuery Python 库下载结果的速度是 Node JS 库的 2 倍
- python - -x 在 sorted 函数的键中是什么意思?
- junit - 使用 Mockito 和 JUNIT 和 CDI 模拟服务
- go - 如何使用 Golang 移位十六进制值?
- python - 从部分 href 下载和保存 PDF?
- stored-procedures - [Amazon](500310) 无效操作:"$$" 处或附近未终止的美元引号字符串
- swift - 结果类型通用参数“T”无法快速推断 5