You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用字符串函数处理API返回数据时遇TypeError问题及日期时间拆分展示优化咨询

Fixing TypeError: Cannot read property 'slice' of undefined & Optimizing Date/Time Display

Why You're Seeing the Error

Let's break down the root cause:

  1. Initial State Mismatch: Your initial state for data is an empty array ([]), but the API returns an object. Before the fetch completes, data.datetime is undefined.
  2. Undefined String Conversion: JSON.stringify(undefined) returns undefined (not a valid string), so mystr is undefined when the component first renders. Calling slice() on an undefined value throws the TypeError.

Step-by-Step Fixes & Optimization

1. Correct Initial State

Change the initial state from an array to an empty object, since the API returns an object:

const [data, setData] = useState({});

2. Add Loading & Error Handling

Before the fetch finishes, your component tries to render data that doesn't exist yet. Add loading and error states to handle this gracefully:

const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

Update your fetch function to set these states:

const fetchTimeZone = () => {
  fetch("http://worldtimeapi.org/api/timezone/Asia/Kolkata")
    .then((response) => {
      if (!response.ok) throw new Error("Failed to fetch time data");
      return response.json();
    })
    .then((json) => {
      setData(json);
      setLoading(false);
    })
    .catch((err) => {
      setError(err.message);
      setLoading(false);
    });
};

3. Replace String Slicing with Date Object (Optimization)

String slicing is fragile—it depends on the exact format of the datetime string. Instead, use JavaScript's built-in Date object to parse and format the datetime reliably:

const date = new Date(data.datetime);
// Format date as YYYY-MM-DD
const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
// Format time as HH:mm:ss
const formattedTime = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;

Full Corrected Code

import React, { useState, useEffect } from 'react';

const TimeZoneComponent = () => {
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchTimeZone = () => {
    fetch("http://worldtimeapi.org/api/timezone/Asia/Kolkata")
      .then((response) => {
        if (!response.ok) throw new Error("Failed to fetch time data");
        return response.json();
      })
      .then((json) => {
        setData(json);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message);
        setLoading(false);
      });
  };

  useEffect(() => {
    fetchTimeZone();
  }, []);

  if (loading) return <div className="timezone">Loading...</div>;
  if (error) return <div className="timezone">Error: {error}</div>;

  const date = new Date(data.datetime);
  const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  const formattedTime = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;

  return (
    <div className="timezone">
      Date: {formattedDate} <br/>
      Time: {formattedTime} <br/>
      Timezone: {data.timezone}
    </div>
  );
};

export default TimeZoneComponent;

Key Takeaways

  • Always match your initial state to the data type you expect from the API.
  • Handle loading and error states to avoid rendering undefined values.
  • Use the Date object for date/time operations instead of string manipulation—it's more reliable and maintainable.

内容的提问来源于stack exchange,提问作者MagnusEffect

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 21:22:49