如何在javascript中读取对象的属性?

问题描述

你好!

我正在使用带有React Context API的React。我的整个应用都有App.js组件。它是功能组件。在其中有状态(useState)用于上下文:

const [contextValue,setContextValue] = useState(null)

还有useEffect

useEffect(() => {
    const wrapper = async () => {
      let data = {};

      const fetchData = () => {
        fetchAbout().then((res) => (data.about = res.data));
        fetchNews().then((res) => (data.news = res.data));
        fetchArticles().then((res) => (data.articles = res.data));
        fetchOffer().then((res) => (data.offer = res.data));
        fetchPortfolio().then((res) => (data.portfolio = res.data));
        fetchQuestions().then((res) => (data.questions = res.data));
      };
      await fetchData();

      console.log(data);
      console.log(data.about);

      setContextValue(data);
    };

    wrapper();
  },[]);

因此,在fetchData函数中,我正在创建data对象的属性。 因此,await fetchData()之后有2个控制台日志。正如预期的那样,首先是记录具有其字段的数据对象:

data object with it's fields


但是console.log(data.about);存在问题,因为它正在记录undefined! 我希望这将是数据对象中about字段的值(例如前console.log中的值)

预先感谢

解决方法

fetchData没有返回承诺,因此您不能“等待”它。 到您console.log(data.about)时,数据尚未填充。 您可以通过

解决它
  const fetchData = () => {
    return Promise.all([
       fetchAbout().then((res) => (data.about = res.data)),fetchNews().then((res) => (data.news = res.data)),fetchArticles().then((res) => (data.articles = res.data)),fetchOffer().then((res) => (data.offer = res.data)),fetchPortfolio().then((res) => (data.portfolio = res.data)),fetchQuestions().then((res) => (data.questions = res.data)),])
  };