首页 > 解决方案 > (反应)TypeError:无法读取未定义的属性“substr”

问题描述

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

我从时间 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>
  );
}

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

标签: javascriptreactjsmethods

解决方案


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

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} />;

}

推荐阅读