【问题标题】:(React) TypeError: Cannot read property 'substr' of undefined(反应)TypeError:无法读取未定义的属性“substr”
【发布时间】:2021-08-05 19:31:03
【问题描述】:

我是网络开发的新手,很高兴收到有关我收到的错误的更多信息。

我从时间 API 获取信息并将它们传递给相关组件。我需要操作数据并从字符串中提取一些信息。

很遗憾,我无法理解自己做错了什么并自己解决问题。

function App() {
const [time, setTime] = useState([]);

const getTime = () =>
    fetch("http://worldtimeapi.org/api/ip")
        .then((res) => res.json())
        .then((data) => setTime(data));

useEffect(getTime, []);

return (
<Clock time={time} />
 )
}



export default function Clock({ time }) {
const extractTime = time.datetime.substr(12, 4);

return (
<div className="time-container">
            <p className="time">{extractTime}</p>
        </div>
    </div>
  );
}

非常感谢任何澄清!谢谢!

【问题讨论】:

    标签: javascript reactjs methods


    【解决方案1】:

    当您第一次渲染时 Clock time 仍然是一个空数组,因为仍在获取数据 - 这是一个异步过程,这就是您收到错误的原因 - 还没有数据 。在尝试返回 Clock 之前,您需要添加类似 if (!time.length) return &lt;div /&gt; 的内容,这样您才能发现该问题。注意:很多人在这里使用“微调器”组件而不是&lt;div /&gt; 来表示正在发生某事。

    function App() {
    
      const [time, setTime] = useState([]);
    
      const getTime = () =>
        fetch("http://worldtimeapi.org/api/ip")
        .then((res) => res.json())
        .then((data) => setTime(data));
    
      if (!time.length) return <div />;
    
      return <Clock time = {time} />;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 2022-09-27
      • 2020-09-07
      • 2021-06-22
      • 2021-07-10
      • 2017-01-01
      • 2021-01-16
      相关资源
      最近更新 更多