如何在React组件中使用getInitialProps

时间:2019-11-11 19:19:30

标签: reactjs axios next.js

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

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;

1 个答案:

答案 0 :(得分:0)

您能尝试一下吗?

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>
  );
}