【问题标题】:XMLHttpRequest GET not working in React.jsXMLHttpRequest GET 在 React.js 中不起作用
【发布时间】:2019-12-22 11:18:00
【问题描述】:

我有一个Profile 课程,像这样:

 class Profile extends React.Component {
    state = {
        email: '',
        userName: '',
        userID: ''
    };

    getData() {
        var request = new XMLHttpRequest();

        request.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };
        request.open('GET', 'http://localhost:8080/user/1');
        request.send();
        console.log(request.responseText);
    }

    render() {
        return ( <
            div >
            this.getData(); <
            /div>

        );
    }
}

问题是它没有在控制台中放任何东西。

虽然http://localhost:8080/user/1 在浏览器中返回给我这个:

{"userID":1,"passwordHash":"5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5","email":"admin@admin.com"}

如何解决这个问题?

【问题讨论】:

    标签: javascript node.js reactjs ecmascript-6 xmlhttprequest


    【解决方案1】:

    我可以解决你的问题,你需要用{this.getData();}包装函数调用

    可以找到一个例子here

    class Profile extends React.Component {
       constructor(props)   {
          super(props);
          this.state = {email:'', userName:'', userID:''};
       }
    
       getData() {
         var request = new XMLHttpRequest();
         console.log("Inside getData method");
    
         request.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
         };
         request.open('GET', 'https://reqres.in/api/products/3', true);
         request.send();
         console.log(request.responseText);
       }
    
       render() {
        return(
         <div>
          <h2>You sample output</h2>
            {this.getData()}
          </div>
        );
       }
    }
    
    
    
    ReactDOM.render(<Profile />, document.querySelector("#container"))
    

    【讨论】:

    • 这看起来更适合我,因为它使用了XMLHttpRequest
    【解决方案2】:

    您应该在 componentDidMount 生命周期方法中使用 AJAX 调用填充数据。这样您就可以在检索数据时使用 setState 更新您的组件。

    react 文档中的示例

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          email: '',
          userName: '',
          userID: '',
          error: null,
          isLoaded: false
        };
      }
    
      componentDidMount() {
    
     fetch("http://localhost:8080/user/1")
          .then(res => res.json())
          .then(
            (result) => {
              this.setState({
                email: result.email,
                userName: result.userName,
                userID: result.userID
              });
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }
    
      render() {
        const { error, isLoaded, email, userName, userID  } = this.state;
        return (
            <ul>
              {email}
              {userName}
              {userID}
            </ul>
        );
      }
    }
    

    【讨论】:

    • 它给了我这个错误TypeError: Cannot read property 'map' of undefined
    • 因为您映射的是对象而不是数组。这只是一个例子
    • @MaifeeUlAsad 只需更新我的答案,您可以再次查看
    猜你喜欢
    • 2011-03-15
    • 1970-01-01
    • 2022-12-12
    • 2018-04-29
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多