为什么产品名称无法删除

问题描述 投票:0回答:1

无法读取 null 的属性(读取“价格”) 类型错误:无法读取 null 的属性(读取“价格”)

屏幕上出现类型错误。

import React, { useEffect ,useState} from 'react';
import PayMockup from '../PayMockup';
import { useParams } from 'react-router-dom';

export default function TotalPayMent(){
    const total=PayMockup;
    const [product, setProduct] = useState(null);
    const {userid} =useParams()
    console.log("userid", userid);

    console.log("totalpay", total.order.products[0].price);

    useEffect(()=>{
     const totalpay = total.order.products.find((product) =>product.id == userid); 
     console.log("totalpay", totalpay);
        setProduct(totalpay)
    },[userid])

    return(
        <div className='total-payment'>
            <p>최종 결제금액</p>
            <div className='totalpay' key={product.id}>
                <p className='price-title'>상품가격</p>
                <p className="product-price">{product.price}</p>
            </div>
        </div>
    )
}
reactjs payment
1个回答
0
投票

发生错误的原因是产品的初始状态为 null,并且您尝试在 useEffect 挂钩有机会更新它之前读取 null 的价格属性。在此更新的代码中,仅当满足以下条件时,组件才会有条件地呈现价格信息:产品不为空。如果产品为空,它将呈现“正在加载...”消息。

import React, { useEffect, useState } from 'react';
import PayMockup from '../PayMockup';
import { useParams } from 'react-router-dom';

export default function TotalPayMent() {
    const total = PayMockup;
    const [product, setProduct] = useState(null);
    const { userid } = useParams();
    console.log("userid", userid);

    useEffect(() => {
        const totalpay = total.order.products.find((product) => product.id == userid);
        console.log("totalpay", totalpay);
        setProduct(totalpay);
    }, [userid]);

    return (
        <div className='total-payment'>
            <p>최종 결제금액</p>
            {product ? (
                <div className='totalpay' key={product.id}>
                    <p className='price-title'>상품가격</p>
                    <p className="product-price">{product.price}</p>
                </div>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
}

© www.soinside.com 2019 - 2024. All rights reserved.