React fetch api(没有钩子)
Posted
技术标签:
【中文标题】React fetch api(没有钩子)【英文标题】:React fetch api (without hooks) 【发布时间】:2020-11-13 09:46:24 【问题描述】:您好,我正在尝试使用 sharepoint 构建 webpart 并做出反应。 但我无法构建简单的 api fetch。
export default class Testing100 extends React.Component<ITesting100Props, >
constructor(props: ITesting100Props)
super(props);
this.state = fetchedData: [] ;
componentDidMount()
fetch(`https://api.randomuser.me/`)
.then((res) => res.json())
.then((fetchedData) => this.setState( fetchedData ));
public render(): React.ReactElement<ITesting100Props>
return (
<p>this.state.fetchedData.results.name.first</p> /*fetchedData is red with error Property 'fetchedData' does not exist on type 'Readonly<>'. */
);
API 输出如下所示
"results":["gender":"female","name":"title":"Miss","first":"Justine","last":"Macdonald","location":"street":"number":3332,"name":"St. Lawrence Ave","city":"Wellington","state":"Yukon","country":"Canada","postcode":"O1T 4H9","coordinates":"latitude":"-63.5927","longitude":"62.6969","timezone":"offset":"+6:00","description":"Almaty, Dhaka, Colombo","email":"justine.macdonald@example.com","login":"uuid":"a90c5dff-dcf6-4c6b-bb82-22e3ed2f930c","username":"blackcat228","password":"longdong","salt":"W7AVyRES","md5":"7ab07000c4c9f6ddb85d296e417f33a6","sha1":"abefc0e0cd002308f9dcad4ce4d91645d0d27231","sha256":"604e2318a0bc7af3df622acdb15f316b42090d1d4eb23b102e415519d52dedd1","dob":"date":"1993-10-31T21:03:14.503Z","age":27,"registered":"date":"2006-04-17T22:55:50.380Z","age":14,"phone":"819-520-7512","cell":"844-873-6971","id":"name":"","value":null,"picture":"large":"https://randomuser.me/api/portraits/women/88.jpg","medium":"https://randomuser.me/api/portraits/med/women/88.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/88.jpg","nat":"CA"],"info":"seed":"723b7f94b557aa40","results":1,"page":1,"version":"1.3"
我想做的只是打印名字,但我无法做到,我会感谢任何帮助。
【问题讨论】:
试试<p>this.state.fetchedData.results[0].name.first</p>
。 results 属性是一个 array 并且您需要首先访问必须包含索引的元素 - 在这种情况下 - 0
【参考方案1】:
你可以这样做
<p>this.state.fetchedData.results[0].name.first</p>
【讨论】:
***.com/questions/47561848/… 是的,我看到了,但我不确定我应该怎么做,因为我有从不同文件导出接口 ITesting100Props description: string; ;【参考方案2】:<p>this.state.fetchedData.results[0].name.first</p>
你应该插入 javascript 表达式。正如我在上面所做的那样。
【讨论】:
我在我的代码中修复了括号(我只是忘了把它放在这里)但是结果[0]没有解决我的问题错误仍然存在并且不知道该怎么做。类型“Readonly”上不存在属性“fetchedData”。 将您的 fetchedData 类型设置为“未知”类型并公开。 我没有在 Typescript 中使用基于类的组件。但我认为分别使用 UseState 和 useEffect hooks 会更容易。以上是关于React fetch api(没有钩子)的主要内容,如果未能解决你的问题,请参考以下文章