反应-TypeError:无法读取未定义的属性“图像”

时间:2020-11-07 12:48:03

标签: javascript html reactjs react-router

因此,我正在为一个补充项目创建一个电子商务商店,但是我遇到了一个问题。 在主页上,我拥有所有产品,并且为产品详细信息创建了一条路线。当我单击其中之一时,它会获得ID,并应输出所有产品详细信息。我在JSON数组“ data.js”中有关于产品的详细信息。

当我单击主页上的产品时,它会显示错误:text = "This is string, remove text after second comma, to be removed." k= (text.find(",")) #find "," in a string m = (text.find(",", k+1)) #Find second "," in a string new_string = text[:m] print(new_string) -在TypeError: Cannot read property 'image' of undefined部分中,我在其中放置return的地方。

但是,当我取消注释它检查产品是否存在的部分(ProductPage.js)时,它仍然输出{product.image},就好像“ data.js”中没有关于产品的任何数据一样。文件。

App.js

"Item does not exist!"

ProductPage.js

<Route path="/product/:id" component={ProductPage}></Route>

Data.js

import React from 'react';
import data from '../data';

export default function ProductPage(props) {
const product = data.products.find((x) => x._id === props.match.params.id);
// if (!product) {
//     return <div>Item does not exist!</div>
// }
return (
    <div>
        <div className="row">
            <div className="col">
                <img src={product.image} alt={product.name}></img>
            </div>
        </div>
    </div>
);
}

谢谢。

2 个答案:

答案 0 :(得分:0)

您需要使用 withRouter 包装您的ProductPage组件,以访问 props.match.params.id

编辑:如果要使用 props.match.params.id 进行比较,请记住它是一个字符串

将您的ProductPage组件更改为:

import React from 'react';
import data from '../data';
import {withRouter} from 'react-router';

function ProductPage(props) {
const product = data.products.find((x) => x._id === props.match.params.id);
return (
    <div>
        <div className="row">
            <div className="col">
                <img src={product.image} alt={product.name}></img>
            </div>
        </div>
    </div>
);
}

export default withRouter(ProductPage);

答案 1 :(得分:0)

从'react-router'导入{withRouter};

这个方法不行,我试过了。

对我有用的解决方案:

不要只使用 product.image 使用 product && product.image。

{product.name}

有关条件渲染 (&&) 的更多信息,请查看以下链接:

What does '&&' operator indicate with { this.props.children && React.cloneElement(this.props.children, { foo:this.foo})