简体   繁体   中英

cannot read property "toFixed" of undefined

I have the following block of code:

export interface Record {
Percentage_Emissions: number;
Percentage_Emissions_Previous: number;
Vs_Previous_Year: number;
}

const Info = ({
  data
}: {
  data: dashboard.Results<Record>;
}) => {
  const styles = Styles(myStyles);
  const record = data.results.records[0];
  let redStyle =
  record.Percentage_Emissions < 0
    ? [styles.textInRed]
    : [styles.textInGreen];
    const percentageText =
    record.Percentage_Emissions === undefined
      ? `-`
      : `${(
          record.Percentage_
Emissions * 100
        ).toFixed(2)}${strings("data.percent")}`;

I just realised that the problem is with the render method, which calls:

 <Text
          style={[styles.text, styles.textLarge]}
        >{`${record.Percentage_Emissions.toFixed(2)}${strings(
          "data.percent"
        )}`}</Text>

I think the problem is that the render method assumes that Percentage_Emissions is defined, but I still don't know how to fix it.

In the emulator, the page crashes because of the error "Cannot read property "toFixed" of undefined. it is supposed to return a dash if no data was found, or else return the rounded information if it is available with conditional formatting. I can't see what is wrong with my code. Does anyone have any ideas on what is happening here?

Split your problem up:

const percentAsString = (n) => (n * 100).toFixed(2) + strings('data.percent');

const safePercentAsString = (n) => (n === undefined) ? '-' : percentAsString(n);

These are trivially unit testable.

Then within your own function, just do:

const percentageText = safePercentAsString(record.Percentage_Emissions);

If you still have problems with the output, you known the problem must lay in the handling of the record object, and not your output code.

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