因此,当我单击复选框时,我一直收到此错误,并且期望的结果将是在单击复选框后,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
    })

关于javascript - 不断收到TypeError:当我单击复选框时,无法读取未定义的 'map'属性,不知道问题出在哪里,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59156289/

10-09 09:11