reactjs - 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
解决方案
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>
)
}
推荐阅读
- swift - IOS <11上似乎忽略了“延迟着陆”属性
- c - 我在重新分配后得到一个断点。为什么?我怎样才能使它正确?
- php - 如何将 svg 显示为具有 URL 中给出的背景颜色的图像
- spring - Spring / IntelliJ 在停止时不会清除会话数据
- firebase - 在 Cloud Firestore 中使用顺序 ID 的限制
- c# - Newtonsoft.Json AttributeProvider 不提供运行时添加的自定义属性
- javascript - 修改后需要下载图片吗?
- reactjs - Redux 表单与 compose 不工作抛出错误
- ios - 在Objective C中创建负数数组
- python - sqlalchemy onupdate inconsistent behavior for Query.update()