首页 > 解决方案 > React JS/Typescript Axios 变量赋值

问题描述

React JS,axios,“response.data.title”在我用axios做的get操作中成功返回。但是,当我将它分配给 title 变量并想在屏幕上显示 {title} 时,什么也没有出现。赋值有问题。

import React, { FC, constructor, useEffect } from 'react'
import axios, { AxiosResponse, AxiosError } from "axios";

interface HowToContactAShopProps {
   title: string
}

const HowToContactAShop: FC<HowToContactAShopProps> = ({ title }) => {

   useEffect(() => {
      axios.get('http://localhost:1337/reviews/1')
     .then((response: AxiosResponse) => {
        title = response.data.title
        console.log(title);
    });
  });

 return (

    <NavbarLayout>

      <H1>How to Contact a Shop</H1>
      <H1>{title}</H1>

  </NavbarLayout>
 )
}
export default HowToContactAShop

标签: reactjstypescriptaxiosuse-state

解决方案


title使用 set state 方法制作变量状态变量并更新标题。

interface HowToContactAShopProps {
}

const HowToContactAShop: FC<HowToContactAShopProps> = () => {
   const [title, setTitle] = useState<string>('');
   useEffect(() => {
      axios.get('http://localhost:1337/reviews/1')
     .then((response: AxiosResponse) => {
        setTitle(response.data.title)
    });
  }, []);

 return (

    <NavbarLayout>

      <H1>How to Contact a Shop</H1>
      <H1>{title}</H1>

  </NavbarLayout>
 )
}

推荐阅读