我正在构建我的React组件,并在尝试使用axios请求并将该响应数据添加到对象时遇到此错误。但是当我尝试console.log对象时,它向我显示了扩展对象时的值,但仍然显示null。
let id, title, channel;
let details = {
timestamp: null,
views: null,
likes: null,
description: null
};
if (active == undefined) {
active = {};
} else {
id = active.id;
title = active.title;
channel = active.channel;
let dataObject = API.get(`videos/${id}`, {
params: {
api_key: "ab4d78b8-e8ff-4392-bff8-21d1058cd420"
}
});
dataObject.then(result => {
let data = result.data;
details.timestamp = data.timestamp;
details.views = data.views;
details.likes = data.likes;
details.description = data.description;
});
}
return (
<div className="videoContent">
<h1 className="videoContent__title">{title}</h1>
<div className="videoContent__details">
<div className="videoContent__details--user">
<p className="channel">By {channel}</p>
<p className="timestamp">{dateFormat(details.timestamp)}</p>
</div>
<div className="videoContent__details--social">
<p className="views">
<img src={viewIcon} alt=""></img>
{/* {details.views} */}
</p>
<p className="likes">
<img src={likeIcon} alt=""></img>
{/* {props.details.likes.toLocaleString()} */}
</p>
</div>
</div>
<div className="videoContent__description">
{/* <p>{details.description}</p> */}
</div>
</div>
);
}
这是我从控制台获得的:
{
timestamp: null,
views: null,
likes: null,
description: null
}
timestamp: 1537003624000
views: "2,043,765"
likes: "400,058"
description: "Luxury is something everyone deserves from time to time. Such
an indulgence can make a vacation a truly rejuvenating experience. This video will
focus a lot on helping the first time or inexperienced traveler head out prepared and
confident in themselves."
__proto__: Object
编辑:我的axios通话:
import axios from "axios";
export default axios.create({
baseURL: "https://project-2-api.herokuapp.com/",
responseType: "json"
});
答案 0 :(得分:0)
JavaScript始终是同步的并且是单线程的。如果您要在页面上执行JavaScript代码块,那么该页面上当前不会执行其他JavaScript。
JavaScript仅在可以进行Ajax调用的意义上是异步的。 Ajax调用将停止执行,其他代码将能够执行,直到调用返回(成功或其他)为止,此时回调将同步运行。此时将不会再运行其他代码。它不会中断当前正在运行的任何其他代码。
要解决您的问题,您应该使用Promise或Async / await,尝试如下修改您的代码:
let dataObject = () => {
return new Promise((resolve, reject) => {
API.get(`videos/${id}`, {
params:{
api_key: "ab4d78b8-e8ff-4392-bff8-21d1058cd420"
}
}, function(error, response, data){
if (error) reject(error);
let content = JSON.parse(data);
let result = content.value;
resolve(result);
})
}
);
};
dataObject(url)
.then(result => {
let data = result.data;
details.timestamp = data.timestamp;
details.views = data.views;
details.likes = data.likes;
details.description = data.description;
return (<div>...</div>)
})
.catch(err => {
console.(error)
});