首页 > 解决方案 > 无法读取 React 应用程序中未定义的图像

问题描述

我使用 filter 方法在数组中挑选出一个特色项目,并使用它在我的 Home 组件中呈现它的状态。我在 MainComponent 中使用 filter 方法,将其传递给 Home 组件,我希望 AddCard 功能组件在其中呈现。我收到“无法读取未定义的图像”的错误消息,所以我假设我在传递道具时做错了。

MainComponent.js

class Main extends Component{
    constructor(props){
        super(props);
        this.state={
            whyfastpack: WHYFASTPACK
        };
    }

    render(){

        const LandingPage =()=>{
            return (
                <Landing />
            );
        };

        const HomePage=()=>{
            return (
                <Home   
                    lightweight={this.state.whyfastpack.filter(lightweight => lightweight.featured)[0]}
                />
            );
        };

        return(
            <div>
                <Header />
                <Switch>
                    <Route exact path='/' component={LandingPage} />
                    <Route path ='/home' component={HomePage} />

HomeComponent.js

   ...
                            </div>
                            <div className='col-md m-1'>
                                <AddCard />
                            </div>
                        </div>


   ....

function RenderCard({ item }) {
    return (
        <Card>
            <CardImg src={this.image} alt={item.name} />
            <CardBody>
                <CardTitle>{item.name}</CardTitle>
                <CardText>{item.comment}</CardText>
            </CardBody>
        </Card>
    );
}


function AddCard(props) {
    return (
        <div className="container">
            <div className="row">
                <div className="col-md m-1">
                    <RenderCard item={props.lightweight} />
                </div>
            </div>
        </div>
    );
}

为什么FastPack.js

export const WHYFASTPACK = [
    {
        id: 0,
        image: 'images/pnw.jpg',
        name: 'Reduce Weight',
        comment: 'Carry only what you need for the day, not a month! With fast-packing you only need to bring enough to get you through each day!',
        featured: true,
    }
]

标签: reactjsreact-router

解决方案


您忽略了将lightweight道具传递给AddCardfrom HomeComponent

<div className='col-md m-1'>
  <AddCard lightweight={this.props.lightweight} />
</div>

推荐阅读