我在閱讀 {find} 時遇到問題。問題出在 ProductDetail.js 中。首先,單擊產品鏈接而不是單擊任何產品以查看詳細資訊。型別錯誤:無法讀取 null 的屬性(讀取“查找”) https://codesandbox.io/s/react-router-product-detail-pages-dynamic-links-forked-y1o0n?file=/src/ProductDetail.js: 418-429
uj5u.com熱心網友回復:
你在你的ProductDetail.js檔案中犯了一些錯誤。
第一的:
您可以使用useEffect鉤子來檢查和比較是否有matching id。
第二:
您可以使用useStatehook 來存盤thisProduct和更新thisProduct值setThisProduct,方法是在JSXElement.
這始終是使用statefor 資料集和獲取的最佳實踐。
這里有更多關于React.Hooks 的資訊
第三:
Price是一個物件,你不能像那樣渲染你的物件,所以在渲染時使用鍵而不是物件。像這樣:{thisProduct?.price?.current?.value}
您可以了解有關可選鏈接的更多資訊
第四:
productId你得到的useParams是字串型別,你的productIdfrom 運動鞋是數字型別。所以你需要productId在像這樣比較時改變你的數字:Number(productId)
了解Js 中的數字
這是你的完整代碼:
// ProductDetail.js
import React, { useContext, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { StateContext } from "./GlobalContext";
function ProductDetail() {
const { productId } = useParams();
const { sneakers } = useContext(StateContext);
const [thisProduct, setThisProduct] = useState({});
useEffect(() => {
if (sneakers) {
const findProduct = sneakers.find((product) => {
return product.id === Number(productId);
});
console.log("findproduct", findProduct);
setThisProduct(findProduct);
}
}, [productId, sneakers]);
return (
<div>
{thisProduct && (
<>
<h1>{thisProduct?.name}</h1>
<p>Price: {thisProduct?.price?.current?.value}</p>
<p>{thisProduct?.description}</p>
</>
)}
</div>
);
}
export default ProductDetail;
uj5u.com熱心網友回復:
完全檢查您的狀態和道具,它沒有向子組件提供有效資料
<StateContext.Provider value={{ sneakers }}>
{console.log(sneakers, "== thisProduct")}
{children}
</StateContext.Provider>
控制臺將顯示您的資料,它變為空,這就是問題所在
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/357448.html
標籤:javascript 反应
上一篇:將時間戳轉換為一個陣列
