繁体   English   中英

从函数外部访问变量 - Javascript、API、XMLHttpRequest

[英]Accessing a variable from outside a function - Javascript, API, XMLHttpRequest

只想从此 XMLHttpRequest 函数访问“数据”变量。 需要使用下面我的“应用程序”反应组件中的数据。

我试过让“让数据”全球化? 但只需要能够在“外部”console.log 所在的函数之外访问它。 目前,它显示未定义。

所以询问如何让我的数据被我的反应组件“App”访问。

抱歉,我是使用此函数获取 API 数据的新手。

感谢您的帮助,如果您需要更多信息,请询问!

const request = new XMLHttpRequest()

request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)

let data

request.onload = function () {
   let data = JSON.parse(this.response)

  if (request.status >= 200 && request.status < 400) {
    data.forEach((movie) => {
      console.log(movie.title)
    })
  } else {
    console.log('error')
  }
}

console.log(data,"outside")

request.send()



    class App extends Component {
        constructor(props) {
          super(props);
          this.state = {
          
          };
        }
        render() {
            return (
                <>
                    <DateRangePickerWrapper value={this.state.child1}/> 
                </>
            )
        }
    }

你在 React 应用程序上使用类编程,所以你必须做这样的事情

import axios from 'axios'

class App extends Component {
 constructor(props){
        super(props);
        this.state = {data: []}

    }

    componentDidMount(){
        axios.get("https://ghibliapi.herokuapp.com/films")
            .then(response =>{
                this.setState({data: response.data});
            })
            .catch(function(error){
                console.log(error)
            })
    }

    componentDidUpdate(){
        axios.get("https://ghibliapi.herokuapp.com/films")
            .then(response =>{
                this.setState({data: response.data});
            })
            .catch(function(error){
                console.log(error)
            })
    }

    
    render() {

       
        
        return (
            <div>
                {data.map(data=> (

                //logic to render the api's data
                
                ))}
                

                    
                
            </div>

            
        )
    }
}

这是怎么做的

import React, { useEffect, useState } from "react";

export default function App() {
  const [readData, writeData] = useState();
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => writeData(json));
  }, []);
  return (
    <>
      <div>title: {readData.title}</div>
      <div>completed: {String(readData.completed)}</div>
    </>
  );
}

沙盒

当我第一次处理异步代码时,我在这个确切的问题上挣扎。

如果您在 React 中有异步代码,则公式很简单。 有一些状态,当异步代码运行时,更新状态并且更改应该反映在您的 jsx 中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM