【问题标题】:Undefined props in componentDidMountcomponentDidMount 中未定义的道具
【发布时间】:2019-07-11 01:57:36
【问题描述】:

这开始变得非常令人沮丧。基本上,我无法在我的子组件中访问props。如果我尝试使用this.props 直接渲染它们,它可以工作,但如果我需要对它们进行额外的处理,或者将它们保存到state,我总是得到未定义的道具。我有一个父组件,看起来像这样:

import React from 'react';

import Title from './EventSubComponents/Title';
import SessionInfo from './EventSubComponents/SessionInfo';
import SessionTime from './EventSubComponents/SessionTime';
import Location from './EventSubComponents/Location';
import Subscribers from './EventSubComponents/Subscribers';

class EventNode extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      'event': [],
    }
  }

  componentDidMount() {
    this.getEvent(this.props.location.selectedEventId);
  }

  getEvent(eventId) {
    fetch('/api/v.1.0/event/' + eventId, {mode: 'no-cors'})
      .then(function(response) {
        if(!response.ok) {
          console.log('Failed to get single event.');
          return;
        }
        return response.json();
      })
      .then((data) => {
        if (!data) {
          return;
        }
        this.setState({
          'event': data
        })
      });
  }

  render() {
    return(
      <div className="event-wrapper">
        <Title 
        title = { this.state.event.title } 
        date = { this.state.event.start }
        />
        <SessionInfo 
          distance = { this.state.event.distance }
          type = { this.state.event.type }
        />
        <SessionTime 
          start = { this.state.event.start }
          end = { this.state.event.end }
        />
        <Location location = { this.state.event.start_location }/>
        <Subscribers 
        subscribers = { this.state.event.subscribers } 
        eventId = { this.state.event._id }
        />
      </div>
    );
  }
}

export default EventNode;

还有我的子组件SessionTime,看起来像这样:

import React from 'react';
import moment from 'moment';

class Title extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      'title': '',
      'date': '',
    }
  }

  componentDidMount() {
    console.log(this.props.title);
    console.log(this.props.date);
    // undefined both props.
    this.convertToTitleDate(this.props.date);
    this.setState({
      'title': this.props.title
    })
  }

  convertToTitleDate(date) {
    var newDate = moment(date).format('dddd, Do MMMM')
    this.setState({
      'date': newDate,
    });
  }

  render() {
    return (
      <div className="event-title-wrapper">
        <h1> { this.state.title } </h1>
        <div className="event-title-date"> { this.state.date } </div>
      </div>
    );
  }
}

export default Title;

谁能解释一下,为什么this.props.datethis.props.title 在我的componentDidMount 函数中都没有定义?我的EventNode 中有更多组件,我也有同样的问题。

componentDidMount 更改为componentWillMount 没有帮助。我相当确定我的父 EventNode 组件有问题,但我不知道在哪里。在EventNoderender()里面定义了所有的状态变量。

【问题讨论】:

    标签: reactjs react-props react-state


    【解决方案1】:

    您将event 初始化为一个空数组,并将this.state.event.startthis.state.event.end 传递给SessionTime,在第一次渲染时它们都是undefined,因为event 尚未加载并且没有数组上的startend 属性。

    你可以改为例如最初将event 设置为null,然后从render 方法返回null,直到加载了event

    示例

    class EventNode extends React.Component {
      state = {
        event: null
      };
    
      // ...
    
      render() {
        const { event } = this.state;
    
        if (event === null) {
          return null;
        }
    
        return (
          <div className="event-wrapper">
            <Title title={event.title} date={event.start} />
            <SessionInfo distance={event.distance} type={event.type} />
            <SessionTime start={event.start} end={event.end} />
            <Location location={event.start_location} />
            <Subscribers
              subscribers={event.subscribers}
              eventId={this.state.event._id}
            />
          </div>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-26
      • 2018-09-20
      • 2020-12-15
      • 1970-01-01
      • 2017-02-06
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      相关资源
      最近更新 更多