javascript 在React componentdidmount函数中将fetch响应分配给setState

iyfamqjs  于 2023-05-27  发布在  Java
关注(0)|答案(2)|浏览(165)

我应该先说我是React的新手。
当一个组件挂载时,我需要获取一个API端点,并将JSON响应分配给状态数据。最后,我需要将JSON响应传递给另一个组件。
我试过把fetch直接放在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 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>
        );
    }
}
ax6ht2ek

ax6ht2ek1#

试试这个.then((response) => response.json()).then((data) => {...}
最好将this.getUrls()更改为this.getUrls(data),因为this.state.data的值可能尚未更新。

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

另外,请记住在constructor()中添加this.state = { data: {}, urls: [] };

h5qlskok

h5qlskok2#

实际上,你正在给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})
 }

相关问题