这是我第一次使用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;
答案 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>
);
}