【问题标题】:How to use getInitialProps in React component如何在 React 组件中使用 getInitialProps
【发布时间】:2020-03-07 11:55:17
【问题描述】:

这是我第一次使用 React 和 Next.js,所以我不是很有经验,但我正在尝试帮助一个使用这两种东西的项目。我需要从端点获取一组艺术家并在ProjectForm 中使用它。 getInitialProps 函数用于在项目的其他地方执行此操作,因此我尝试效仿,但不确定如何将此数据传递给 ProjectForm。我尝试过类似const ProjectForm = (props: ProjectFormProps, artists) 并将artists: artists 添加到ProjectFormProps,但没有骰子。如何使用从ProjectForm 中的getInitialProps 函数获得的artists 数据?任何帮助将不胜感激!

import React, { useState, useEffect, useReducer } from 'react';
import axios from 'axios';

interface ProjectFormProps {
  entity: any;
  user: any;
  projectTypes?: any;
  handleButtonClick?: any;
  isNew?: boolean,
  onSubmitForm?: Function,
  onChange?: Function,
};

const ProjectForm = (props: ProjectFormProps) => {

  console.log(artists);

  return (
    <h1>Artists</h1>
  );
}

ProjectForm.getInitialProps = async ({ req }) => {
  const baseUrl = req ? `${req.protocol}://${req.get('Host')}` : '';
  const artists = await axios.get(`${baseUrl}/api/artists`)
    .then(res => res.data)
    .catch(err => console.error(err, 'Unable to retrieve artists from API.'));
  return {
    artists
  };
};

export default ProjectForm;

【问题讨论】:

    标签: reactjs axios next.js


    【解决方案1】:

    你能试试这个吗:

    interface ProjectFormProps {
      entity: any;
      user: any;
      projectTypes?: any;
      handleButtonClick?: any;
      isNew?: boolean,
      onSubmitForm?: Function,
      onChange?: Function,
      artists?: any
    };
    
    
    const ProjectForm = (props: ProjectFormProps) => {
      console.log(props.artists);
    
      return (
         <h1>Artists</h1>
      );
    }
    

    【讨论】:

    • 检查你是否真的让艺术家进入 getInitialProps
    • 如果是,那么代替console.log(props.artists);检查 console.log(props);艺术家参数
    • console.log(props.artists); 给了我undefined,当我检查console.log(props); 时,我没有看到艺术家参数。
    • 是的,我也尝试过沙盒。我认为问题在于我们的应用程序的设置,因为由于某种原因 getInitialProps 根本没有被执行。可能你需要检查安装并确保一切正常(主要是 getInitialProps 被执行)
    猜你喜欢
    • 2017-04-14
    • 2019-05-08
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多