首页 > 解决方案 > reactJS render() 方法中未定义属性值

问题描述

我正在尝试构建一个简单的反应类,该类在渲染时会根据从其父组件在道具中接收到的图像路径返回标题和图像。

每次我尝试访问属性 this.props.eImage(本地图像路径)时,所述属性的值都是未定义的,如 eImage:前两次渲染未定义(组件由于未知原因渲染了 4 次)。我可以使用该物业,但由于某种原因无法获得其价值。

这会导致渲染方法抛出错误“找不到模块‘未定义’。

我尝试使用诸如 getDerivedState 和组件 willRecieveProps 之类的生命周期方法首先将图像路径存储在状态中,然后在渲染中使用它,但无济于事,两者都有相同的结果。

这非常令人沮丧,因为这是一项简单的任务,但我无法让它发挥作用。请帮忙。缩短的代码是:

家长:

import React, {Component} from 'react';
import Title from './Title/Title.js';
import Description from './Description/Description.js';
import OrderSection from './OrderSection/OrderSection.js';
import './excursionStyle.css';

const excursionList = [
  {
    excTitle : "Музейный Дрезден",
    excDescription: `Дрезденская картинная галерея, как всегда, радует :)`} 
  ]

class Excursion extends Component {
    constructor(){
        super();
        this.state = {
        };
      };

    getCurrentIndex = (name) => {
      return excursionList.find(exc =>
        exc.excTitle === name
      )
    }

  componentDidMount() {   
      const currentExcursion = this.getCurrentIndex(this.props.match.params.name);
      this.setState(currentExcursion);
    };
    
    render(){    
      return (
          <div className="body">
            <div className="excursion">
            <Title eTitle={this.state.excTitle} eImage={this.state.excImageUrl}/>
                <Description eDescription = {this.state.excDescription}/>
                <OrderSection eTitle = {this.state.excTitle}/>
          </div>
          </div>
            );
    }
        
}

孩子 :

import React, {Component} from 'react';
import './Title.css';

class Title extends Component{
    constructor(props){
        super(props);     
    }
    render() {  
        console.log(this.props)
        return (
            <div>
            <header className = "flex">
                <p className = "f2 b">{this.props.eTitle}</p>
            </header>
            <div>
                    <img src={require(this.props.eImage)}></img>                                                                      
            </div>
            </div>    
        );
    }
}

export default Title;

标签: javascriptreactjs

解决方案


您的Excursion组件以这种状态开始:

this.state = {
};

这意味着当它 render 时Title, usingthis.state.excImageUrl正在访问 state 对象上不存在的属性,从而产生 value undefined。所以你的Title组件会看到eImagevalue undefined

如果Title需要该属性,则在拥有它之前无需渲染Title。这通常是通过某种守卫来完成的,例如(in Excursion):

render(){    
  const eImage = this.state.excImageUrl;
  return (
      <div className="body">
        <div className="excursion">
        {eImage && <Title eTitle={this.state.excTitle} eImage={eImage}/>
            <Description eDescription = {this.state.excDescription}/>
            <OrderSection eTitle = {this.state.excTitle}/>
        }
      </div>
      </div>
        );
}

注意{eImage && <Title ... />}结构,它是守卫。React 会忽略表达式值为 id undefinedornull的表达式占位符false,因此如果eImageundefined{eImage && <Title ... />}将是undefinedTitle不会使用)。但如果eImage是非空字符串(例如),则{eImage && <Title ... />}结果为Title.


旁注:

...组件由于未知原因被渲染了 4 次...

编写的方式Excursion是,它总是至少被渲染两次:一次没有任何东西 on state,然后再次在componentDidMount's 状态更新之后。每次它的 props 改变时它也会被渲染,所以如果(例如)它的父组件给它一个match值开始,然后用另一个值更新它,它可能会渲染 3 次。如果父组件更新match不止一次...


推荐阅读