英文:
Assign fetch response to setState in React componentdidmount function
问题
I should start out by saying I'm pretty new to React.
当组件挂载时,我需要获取一个API端点,并将JSON响应分配给状态数据。最终,我需要将JSON响应传递给另一个组件。
我尝试将获取直接放在componentDidMount()
函数中,但没有成功。下面,您可以看到在控制台中生成的错误。这是在第25行console.log("This data => " + JSON.stringify(this.state.data));
处生成的错误。
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'data')
任何关于如何将/profile/:id
的响应传递给ResultsDashboard
组件的见解都将有帮助。
以下是我组件的代码。
import React from 'react';
import ReactDOM from 'react-dom';
import { Tabs } from 'antd';
import { ResultsDashboard } from './ResultsDashboard.js';
export class TestResults extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null, // Initialize data as null
urls: null, // Initialize urls as null
};
}
getProfileData() {
console.log("Making a fetch for URL /profile/" + window.location.href.split('/')[4])
fetch('/profile/' + window.location.href.split('/')[4])
.then(response => response.json()) // Parse the response as JSON
.then(data => {
this.setState({ data: data }); // Set data state with the JSON response
this.setState({ urls: this.getUrls() }); // Set urls state by calling getUrls
})
.catch(error => {
console.error("Error fetching data:", error);
});
}
componentDidMount() {
this.getProfileData();
}
getUrls() {
const urls = [];
console.log("This data => " + JSON.stringify(this.state.data));
if (this.state.data) { // Check if data is not null
for (var x = 0; x < this.state.data.length; x++) {
urls.push(this.state.data[x].url)
}
}
return urls;
}
render() {
return (
<div>
<Tabs
defaultActiveKey="1"
type="card"
size="large"
items={this?.state?.urls?.map((url, index) => {
return {
label: `${url.substr(0, 75)}`,
key: index,
children: <ResultsDashboard testIndex={index} aggregateData={this.state.data} />,
};
})}
/>
</div>
);
}
}
在这个修复后的代码中,我初始化了data
和urls
状态为null
,并在getProfileData
函数中正确处理了响应数据。此外,我还添加了对data
是否为null
的检查,以避免在获取数据之前访问它。
英文:
I should start out by saying I'm pretty new to React.
When a component mounts, I need to fetch an API endpoint, and assign the JSON response to state data. Ultimately, I need to pass the JSON response to another component.
I've tried putting the fetch directly in the componentDidMount() function but that did not work. Below, you can see the error generated in the console. This is at line 25 console.log("This data => " + JSON.stringify(this.state.data));
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'data')
Any insight into how I can pass the response of /profile/:id to the ResultsDashboard component would be helpful.
Below is the code I have for my component.
import ReactDOM from 'react-dom';
import { Tabs } from 'antd';
import { ResultsDashboard } from './ResultsDashboard.js'
export class TestResults extends React.Component {
constructor(props){
super (props);
}
getProfileData (){
console.log("Making a fetch for URL /profile/" + window.location.href.split('/')[4])
fetch('/profile/' + window.location.href.split('/')[4]).then( response => {
console.log("Response in Fetch => " + JSON.stringify(response))
this.setState({data: response.json()})
this.setState({urls: this.getUrls()});
});
}
componentDidMount(){
this.getProfileData();
}
getUrls(){
const urls = [];
console.log("This data => " + JSON.stringify(this.state.data));
for (var x = 0; x < this.state.data.length; x++){
urls.push(this.state.data[x].url)
}
return urls
}
render (){
return(
<div>
<Tabs
defaultActiveKey="1"
type="card"
size="large"
items={this?.state?.urls?.map((url,index) => {
return {
label: `${url.substr(0,75)}`,
key: index,
children: <ResultsDashboard testIndex={index} aggregateData={this.state.data}/>
};
})}
/>
</div>
);
}
}
</details>
# 答案1
**得分**: 1
Sure, here are the translated parts:
尝试这个 `.then((response) => response.json()).then((data) => {...}`
最好将 `this.getUrls()` 更改为 `this.getUrls(data)`,因为 `this.state.data` 的值可能尚未更新。
```js
getProfileData() {
console.log("为URL /profile/进行获取:" + window.location.href.split("/")[4]);
fetch("/profile/" + window.location.href.split("/")[4])
.then((response) => response.json())
.then((data) => {
console.log("在Fetch中的响应 => " + JSON.stringify(response));
this.setState({ data: data });
this.setState({ urls: this.getUrls(data) });
});
}
此外,请记得在 constructor()
中添加 this.state = { data: {}, urls: [] };
。
英文:
Try this .then((response) => response.json()).then((data) => {...}
And its better to change this.getUrls()
to this.getUrls(data)
, cause the value of this.state.data
might not be update yet.
getProfileData() {
console.log("Making a fetch for URL /profile/" + window.location.href.split("/")[4]);
fetch("/profile/" + window.location.href.split("/")[4])
.then((response) => response.json())
.then((data) => {
console.log("Response in Fetch => " + JSON.stringify(response));
this.setState({ data: data });
this.setState({ urls: this.getUrls(data) });
});
}
Also, remember to add this.state = { data: {}, urls: [] };
in constructor()
.
答案2
得分: 0
实际上,你正在将一个函数赋给 urls 变量。
你可以尝试在 getUrls 函数中使用 this.setState,将 urls 变量赋值,并将数据作为参数传递。
getProfileData () {
console.log("Making a fetch for URL /profile/" + window.location.href.split('/')[4]);
fetch('/profile/' + window.location.href.split('/')[4]).then(response => {
console.log("Response in Fetch => " + JSON.stringify(response));
this.setState({ data: response.json() });
this.getUrls(response.json());
});
}
getUrls(data) {
const myVar = [];
console.log("This data => " + JSON.stringify(data));
for (var x = 0; x < data.length; x++) {
myVar.push(data[x].url);
}
this.setState({ urls: myVar });
}
请注意,我已经将代码中的 HTML 实体引用(如 "
和 <
)转换为正常的字符,以便更容易阅读和理解。
英文:
In fact you are assigning a function to urls.
You can try using this.setState in the getUrls function assigning urls variable and passing data as argument
getProfileData (){
console.log("Making a fetch for URL /profile/" + window.location.href.split('/')[4])
fetch('/profile/' + window.location.href.split('/')[4]).then( response => {
console.log("Response in Fetch => " + JSON.stringify(response))
this.setState({data: response.json()})
this.getUrls(response.json());
});
}
getUrls(data){
const myVar = [];
console.log("This data => " + JSON.stringify(data));
for (var x = 0; x < data.length; x++){
myVar.push(data[x].url)
}
this.setState({urls: myVar})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论