javascript - (反应)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>
);
}
任何澄清都非常感谢!谢谢!
解决方案
当您第一次渲染时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} />;
}
推荐阅读
- grafana - 选择比给定时间更新的普罗米修斯警报
- scala - Scala:从 dataframe.foreach 访问/编辑地图
- tree - 使用 HyperGraphQL 检索父母和孩子
- rest - 通过 REST api (v2) 将文章发布到公司 LinkedIN 页面
- spring-boot - 当从控制器启动的作业失败时,如何防止弹簧批处理关闭应用程序?
- django - 在 Django 部署期间配置不正确的 urls.py (Django 2.1)
- websocket - Websocket 握手:“Sec-WebSocket-Accept”标头值不正确
- python - Numpy:将列表转换为方形数组
- python - Python中具有不同签名的钻石继承
- css - React-Bootstrap 的 Select 元素的验证未对齐