将获取的响应分配给React组件的componentDidMount函数中的setState。

huangapple go评论65阅读模式
英文:

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>
        );
    }
}

在这个修复后的代码中,我初始化了dataurls状态为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(&quot;This data =&gt; &quot; + JSON.stringify(this.state.data));

Uncaught (in promise) TypeError: Cannot read properties of null (reading &#39;data&#39;)

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 &#39;react-dom&#39;;
import {  Tabs } from &#39;antd&#39;;
import { ResultsDashboard } from &#39;./ResultsDashboard.js&#39;
export class TestResults extends React.Component {
constructor(props){
super (props);
}
getProfileData (){
console.log(&quot;Making a fetch for URL /profile/&quot; + window.location.href.split(&#39;/&#39;)[4])
fetch(&#39;/profile/&#39; + window.location.href.split(&#39;/&#39;)[4]).then( response =&gt; {
console.log(&quot;Response in Fetch =&gt; &quot; + JSON.stringify(response))
this.setState({data:  response.json()})
this.setState({urls: this.getUrls()}); 
});
}
componentDidMount(){
this.getProfileData();
}
getUrls(){
const urls = [];
console.log(&quot;This data =&gt; &quot; + JSON.stringify(this.state.data));
for (var x = 0; x &lt; this.state.data.length; x++){
urls.push(this.state.data[x].url)
}
return urls
}
render (){
return(
&lt;div&gt;
&lt;Tabs
defaultActiveKey=&quot;1&quot;
type=&quot;card&quot;
size=&quot;large&quot;
items={this?.state?.urls?.map((url,index) =&gt; {
return {
label: `${url.substr(0,75)}`,
key: index,
children: &lt;ResultsDashboard testIndex={index} aggregateData={this.state.data}/&gt;
};
})}
/&gt;
&lt;/div&gt;
);
}
} 
</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) =&gt; response.json()).then((data) =&gt; {...}

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(&quot;Making a fetch for URL /profile/&quot; + window.location.href.split(&quot;/&quot;)[4]);
  fetch(&quot;/profile/&quot; + window.location.href.split(&quot;/&quot;)[4])
    .then((response) =&gt; response.json())
    .then((data) =&gt; {
      console.log(&quot;Response in Fetch =&gt; &quot; + 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 实体引用(如 &quot;&lt;)转换为正常的字符,以便更容易阅读和理解。

英文:

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(&quot;Making a fetch for URL /profile/&quot; + window.location.href.split(&#39;/&#39;)[4])
fetch(&#39;/profile/&#39; + window.location.href.split(&#39;/&#39;)[4]).then( response =&gt; {
console.log(&quot;Response in Fetch =&gt; &quot; + JSON.stringify(response))
this.setState({data:  response.json()})
this.getUrls(response.json()); 
});
}
getUrls(data){
const myVar = [];
console.log(&quot;This data =&gt; &quot; + JSON.stringify(data));
for (var x = 0; x &lt; data.length; x++){
myVar.push(data[x].url)
}
this.setState({urls: myVar})
}

huangapple
  • 本文由 发表于 2023年5月25日 08:22:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定