首页 > 解决方案 > 为什么复选框不检查?(反应)

问题描述

我遇到奇怪的情况,我的 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
    })

在此处输入图像描述

标签: reactjscheckboxreact-hooks

解决方案


最后,找出了问题所在,所以事情是关于<React.StrictMode>。唯一的区别是 index.js 在我的项目中运行良好

ReactDOM.render(<App />, document.getElementById('root'));

在其他我有

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

这也是组件渲染两次的原因。

所以删除<React.StrictMode>标签是删除问题:)


推荐阅读