反应 "cannot destructure property"

React "cannot destructure property"

所以我正在尝试学习 React 并且我正在学习一个教程,我跟着教程做所有事情,这个人保存更改并编译,但是我的给出了这个错误: TypeError: Cannot destructure property 'text' of 'seasonConfig[season]' as it is undefined.

这是我要渲染的组件:

import React from 'react';

const seasonConfig = {
  summer: {
    text: '',
    iconName: 'sun'
  },
  winter: {
    text: '',
    iconName: 'snowflake'
  }
};

const getSeason = (lat, month) => {
  if (month > 2 && month < 9) {
    return lat > 0 ? 'summer ' : 'winter';
  } else {
    return lat > 0 ? 'winter ' : 'summer';
  }
};

const SeasonDisplay = (props) => {
  const season = getSeason(props.lat, new Date().getMonth());
  const { text, iconName } = seasonConfig[season];

  return (
    <div>
      <i className={` massive ${iconName} icon`} />
      <h1>{text}</h1>
      <i className={` massive ${iconName} icon`} />
    </div>
  );
};

export default SeasonDisplay;

去掉if条件中summer和winter之后的space:

const getSeason = (lat, month) => {
  if (month > 2 && month < 9) {
    return lat > 0 ? 'summer' : 'winter'; // 'summer ' => 'summer'
  } else {
    return lat > 0 ? 'winter' : 'summer'; // 'winter ' => 'winter'
  }
};

或者如果我们真的需要 space,也可以 seasonConfig[season.trim()]

Try this:
import { React } from "react";

const seasonConfig = {
  Summer: {
    text: "Lets hit beach",
    iconName: "sun",
  },
  Winter: {
    text: " Its Winter",
    iconName: "snowflake",
  },
};

const getSeason = (lat, month) => {
  if (month > 2 && month < 9) {
    return lat > 0 ? "summer" : "winter";
  } else {
    return lat > 0 ? "winter" : "summer";
  }
};
const SeasonDisplay = (props) => {
  const season = getSeason(props.lat, new Date().getMonth());
  console.log(season);
  const text = season === "winter" ? "Burr, Its Chilly" : "Lets hit th e beach";
  const icon = season === "winter" ? "snowflake icon" : "sun icon";

  return (
    <div>
      <i className={icon} />
      <h1>{text}</h1>

      <i className={icon} />
    </div>
  );
};
export default SeasonDisplay;