繁体   English   中英

不断收到TypeError:当我单击复选框时无法读取未定义的属性“地图”,不知道问题出在哪里

[英]Keep getting TypeError: Cannot read property 'map' of undefined when I click on checkbox, dont know where the problem is

因此,当我单击复选框时,我不断收到此错误,并且期望的结果是单击复选框后,active 的属性应更改为相反。 即使我在单击复选框后删除了 activeHandler 函数,我也会收到相同的错误,但现在对于 tbody 中产品的初始映射

const ProductList = props => {
const [products, setProducts] = useState(
    [
        {
            id: 1,
            name: 'Product 1',
            ean: 242355,
            type: 'Food',
            weight: 24,
            color: 'blue',
            active: true,
            quantity: 2,
            price: 25
        },
        {
            id: 2,
            name: 'Product 2',
            ean: 57434,
            type: 'Food',
            weight: 48,
            color: 'red',
            active: false,
            quantity: 5,
            price: 12
        }
    ]
);

const activeHandler = productId => {
    setProducts(prevState => {
        const updatedProducts = prevState.products.map(prod => {
            if (prod.id === productId) {
                prod.active = !prod.active
            }
            return prod
        })
        return {
            products: updatedProducts
        }
    })
}

return (
    <div>
        <table className="table">
            <thead>
                <tr>
                <th scope="col">Name</th>
                <th scope="col">EAN</th>
                <th scope="col">Type</th>
                <th scope="col">Weight</th>
                <th scope="col">Color</th>
                <th scope="col">Active</th>
                <th></th>
                </tr>
            </thead>
            <tbody>
            {products.map(product => (
                <tr key={product.id}>
                <td>{product.name}</td>
                <td>{product.ean}</td>
                <td>{product.type}</td>
                <td>{product.weight}</td>
                <td>{product.color}</td>
                <td>
                    <input type="checkbox" checked={product.active} onChange={() => activeHandler(product.id)} />
                </td>
                <td>
                <button className="btn btn-secondary mr-1" disabled={product.active}>VIEW</button>
                <button className="btn btn-primary mr-1" disabled={product.active}>EDIT</button>
                <button className="btn btn-danger" disabled={product.active}>DELETE</button>
                </td>
                </tr>
            ))     
            }
            </tbody>
       </table>
    </div>
)

}

在这种情况下,您的prevState是实际数组,因此您应该映射它并将其作为新状态而不是具有products键的对象返回:

setProducts(prevState => {
        const updatedProducts = prevState.map(prod => {
            if (prod.id === productId) {
                prod.active = !prod.active
            }
            return prod
        })
        return updatedProducts
    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM