componentDidMount中的未定义道具

时间:2019-02-17 14:57:36

标签: reactjs react-props react-state

这开始变得令人沮丧。基本上,我无法访问子组件中的class User < ApplicationRecord devise :invitable, :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :omniauthable validates :fullname, presence: true, length: { minimum: 4 } validates_acceptance_of :terms_of_service has_many :services has_many :reservations has_many :articles has_many :lists end 。如果我尝试直接使用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 EventNode内部定义了所有状态变量。

1 个答案:

答案 0 :(得分:0)

您将event初始化为一个空数组,并将this.state.event.startthis.state.event.end传递给SessionTime,自{{ 1}}尚未加载,并且数组上没有undefinedevent属性。

您可以改为首先将start设置为end,然后从render方法返回event,直到加载null

示例

null