next.js 在React容器内使用useEffect()中的API请求加载的变量

7xllpg7q  于 2023-06-05  发布在  React
关注(0)|答案(1)|浏览(192)

基本上,我在useEffect()中有一个API请求,所以它在页面加载之前加载所有“notebook”,这样我就可以显示它们了。

useEffect(() => {
   getIdToken().then((idToken) => {
        const data = getAllNotebooks(idToken);
        const jsonData = JSON.stringify(data, null, 2);
        notebooks = JSON.parse(jsonData) as [Notebook, Withdraw[]][];
   });
}

如何在代码中使用这个notebook列表,以便在标签中使用它?
我是React的初学者,所以除了在useEffect()中调用函数外,我没有做太多事情。

**更新:**根据要求,这里是getAllNotebooks核心函数及其用例,以及在useEffect()中调用的函数:
withdraw_repository_http

async getAllNotebooks(idToken: string): Promise<[Notebook, Withdraw[]][]> {
    var notebooks: [Notebook, Withdraw[]][] = [[new Notebook({numSerie : '34000', isActive: false}), [new Withdraw({numSerie : '34000', email: 'erro@maua.br', withdrawTime: Date.now(), finishTime: null})]]];
    try {
      const url = process.env.NEXT_PUBLIC_API_URL + '/get-all-notebooks';
      const { data, status} = await axios.get<[Notebook, Withdraw[]][]>(url, {headers : {'Authorization' : `Bearer ${idToken}'`}});
      console.log('response status is', status);
      if (status === 200) {
          // console.log('response data is', data);
          const jsondata = JSON.stringify(data, null, 2);
          notebooks = JSON.parse(jsondata).notebooks as [Notebook, Withdraw[]][];
          console.log('notebooks is', notebooks);
          return notebooks;
      }
      else {
          console.log('response data is', data);
      }
    }
    catch (error) {
      if (axios.isAxiosError(error)) {
          console.log('error response is', error);
  } else {
          console.log('unknown error');
          console.log(error);
          
      }
    }
    return notebooks;
  }

获取所有笔记本用例

import { IWithdrawRepository } from '../domain/repositories/withdraw_repository_interface';

export class GetAllNotebooksUsecase {
  constructor(private withdrawRepo: IWithdrawRepository) {}

  async execute(idToken: string) {
    const withdraws = await this.withdrawRepo.getAllNotebooks(idToken);
    return withdraws;
  }
}

withdraw_provider

async function getAllNotebooks(idToken: string){
    try {
      const notebooks = await getAllNotebooksUsecase.execute(idToken);
      setNotebooks(notebooks);
      return notebooks;
    }
    catch (error: any) {
      console.log(`ERROR PROVIDER: ${error}`);
      const setError = error;
      setError(setError);
      return [];
    }
  }
ojsjcaue

ojsjcaue1#

const [notebooks, setNotebooks] = useState([]); // initialize notebooks with empty array

useEffect(() => {
   getIdToken().then((idToken) => {
      const data = getAllNotebooks(idToken);
       // I think you don't need this line
       // const jsonData = JSON.stringify(data, null, 2);

      setNotebooks(data);
   });
},[]); // empty brackets here means: useEffect executes only once on load component

// render notebooks using JSX (xml inside javascript)
return {notebooks.map((notebook, index) => {
    <div>
       <h1>My notebook number {index}</h1>
       <h3>This noteboot's name is: {notebook.name}</h3>
       etc..
    </div>
})};

希望这对你有帮助,任何疑问都不要犹豫回答。

相关问题