首页 > 解决方案 > 反应“不能破坏财产”

问题描述

所以我正在尝试学习 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;

标签: javascriptreactjsobjectjsxdestructuring

解决方案


在 if 条件下删除夏季和冬季后的空间:

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

或者,如果我们真的需要空间,也可以这样做seasonConfig[season.trim()]


推荐阅读