我是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
仍然是一个空数组,因为数据仍在提取中-这是一个异步过程,这就是您收到错误的原因-还没有数据。在尝试返回Clock
之前,您需要添加类似if (!time.length) return <div />
的内容,以便发现该问题。注意:很多人使用CCD_;"旋转器";组件,以指示正在发生。
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} />;
}