简体   繁体   中英

REACT-Native conditional props throwing error

I'm fairly new REACT/REACT-Native developer. I'm building a React-Native app and I have a form that is used to create a new budget or edit a budget. I started out simple and had two separate components for each create and edit functions. I got all my functionality working so I started refactoring my code to make a resuable component out of the budget form. I created a new component for the budget form. In the budget form, I setup my state as shown below. When the "create" form is used the budget props are null, as nothing is passed into the component. When the "Edit" form is used the budget props are passed in.

state = {
formMode: this.props.formMode,
budget: {
  id: this.props.budget.BudgetId ? this.props.budget.BudgetId : "",
  name: this.props.budget.Name ? this.props.budget.Name : "",
  color: this.props.budget.Color
    ? this.props.budget.Color
    : this.backgroundColors[0],
  type: this.props.budget.Type ? this.props.budget.Type : "",
  startDate: this.props.budget.StartDate ? this.props.budget.StartDate : "",
  endDate: this.props.budget.EndDate ? this.props.budget.EndDate : "",
},
deviceLocale: "",
datepickerMode: "date",
showStartDatePicker: false,
showEndDatePicker: false,
};

I call the "Create" form from my parent component as shown below

<BudgetForm formMode={Constants.FORM_Mode_Add} />

I call the "edit" form from my parent component as shown below

<BudgetForm formMode={Constants.FORM_Mode_Edit} budget={this.props.list}/>

When I open the form for "create" I get this error:

TypeError: undefined is not an object (evaluating '_this.props.budget.BudgetId')

I'm using this conditional ternary operator on my props in another form in my app and its working fine there. I cannot seem to figure out what is the issue here?

I solved my issue by changing the state object in my BudgetFrom component as shown below.

constructor(props) {
super(props);
this.state = {
  formMode: this.props.formMode,
  id: this.props.id ? this.props.id : "",
  name: this.props.name ? this.props.name : "",
  color: this.props.color ? this.props.color : backgroundColors[0],
  type: this.props.type ? this.props.type : "",
  startDate: this.props.startDate ? this.props.startDate : "",
  endDate: this.props.endDate ? this.props.endDate : "",
  deviceLocale: "",
  datepickerMode: "date",
  showStartDatePicker: false,
  showEndDatePicker: false,
};

}

By not having the "budget" object within state as "child" object it seemed to fix the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM