简体   繁体   English

如何在React JS中使用变量

[英]How to use variable in react js

import React from 'react'
import { Link } from 'react-router'

var result;var response;var jsonString ;var msg;

var xhr = new XMLHttpRequest();
var xhrPost = new XMLHttpRequest();

function xhrGetCall(getUrl){
  xhr.onreadystatechange = function() {
      if (xhr.readyState == XMLHttpRequest.DONE) {
          result = xhr.responseText;
          jsonString = JSON.parse(result);
          console.log('API data retrieved:'+jsonString);
          return result;
      }
  }
  xhr.open('GET', getUrl, true);
  xhr.setRequestHeader("Access-Control-Allow-Origin", true);
  xhr.setRequestHeader( 'Content-Type', 'application/json' );
  xhr.send(null);
  xhr.onerror = function(xhr, textStatus, errorThrown) {
    console.log( 'The data failed to load :('+JSON.stringify(xhr));
  };
};

function xhrPostCall(jsonInput, postUrl){

  xhrPost.open("POST",postUrl, true);
  xhrPost.setRequestHeader("Content-type", "application/json");
    xhrPost.onreadystatechange = function() {
      if(xhrPost.readyState == XMLHttpRequest.DONE && xhrPost.status == 200) {
        msg="succesful!";
          console.log('posting succesful'+jsonInput);
      }
            else {
            msg="failed!";
            alert('msg is:'+msg);
            console.log('posting unsuccesful'+msg);
            }
  }
  xhrPost.send(jsonInput);
    return msg;
}

class AddDetailsModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {UserName: ''};
        this.handleChangeUserName = this.handleChangeUserName.bind(this);

    this.handleSubmit = this.handleSubmit.bind(this);
        this.handleClick=this.handleClick.bind(this);

        xhrGetCall(this.props.getUrl);
        xhr.onload = function() {
         response = JSON.parse(xhr.responseText);
         this.setState({apiReturnValue:jsonToHtmlSelect(response)});
     }.bind(this);
  }
    componentDidMount(){

    }
    handleChangeUserName(event) {
    this.setState({UserName: event.target.value});
  }


  handleSubmit(event) {
        var str = {"UserName": this.state.UserName};
        var json = JSON.stringify(str);
    xhrPostCall(json,this.props.postUrl);
        this.setState({msg:xhrPostCall()});
        console.log("testing: msg:"+msg);

        $('#AddDetailsModal').on('hidden.bs.modal', function (e) {
  $(this)
    .find("input,textarea")
       .val('')
       .end()
    .find("input[type=checkbox], input[type=radio]")
       .prop("checked", "")
       .end();
         })


  }

  render() {

    return (
            <div>
            <div id="AddDetailsModal" className="modal fade" role="dialog">
            <div className="modal-dialog">
                <div className="modal-content">
                <div className="modal-header">
                      <button type="button" className="close" data-dismiss="modal">&times;</button>
                      <h4 className="modal-title">Add Details</h4>
                  </div>

            <div className="modal-body">

        <div className="form-group">
          <label className="col-sm-0 control-label" htmlFor="textinput"> Name : &nbsp; </label>
          <input type="text" value={this.state.UserName} onChange={this.handleChangeUserName}  placeholder="Name" className="form-control"></input>
        </div>

            <div className="modal-footer">
                  <button type="submit" className="btn btn-default" data-dismiss="modal">Cancel</button>
                  <button type="submit" value="submit" onClick={this.handleSubmit} className="btn btn-primary" data-dismiss="modal" data-toggle="modal" href="#AddMsgModal">Submit</button>
            </div>
            </div>
      </div>
    </div>

    <div id="AddMsgModal" className="modal fade" role="dialog">
    <div className="modal-dialog">
        <div className="modal-content">

            <div className="modal-header">
                        <button type="button" className="close" data-dismiss="modal">&times;</button>
                        <h4 className="modal-title">Message Heading</h4>
                </div>

                <div className="alert alert-success">
                {msg}
                </div>

    <div className="modal-footer">
                <button type="submit" className="btn btn-default" data-dismiss="modal">Cancel</button>
    </div>
</div>
</div>
</div>

 </div>


    );
  }
}


export default AddDetailsModal;

I have made a react component "AddDetailsModal" which is bootstrap form modal on successful or unsuccessful submission of the form by handleSubmit() function the other modal "AddMsgModal" should come up showing the msg. 我已经制作了一个反应组件“ AddDetailsModal”,它是通过handleSubmit()函数成功或不成功提交表单时引导表单模式的组件,其他模式“ AddMsgModal”应显示为msg。

i am not able to access the msg variable declared in function xhrPostCall in the render() of react js. 我无法访问react js的render()中的函数xhrPostCall中声明的msg变量。

Kindly let me know how to access that variable there? 请让我知道如何在那里访问该变量?

First - use some labriry like fetch , to create some ajax requests. 首先 -使用诸如fetch之类的工具来创建一些ajax请求。

Second - if you want to create it by yourself use Promise to create async operations: 其次 -如果要自己创建它,请使用Promise创建异步操作:

return new Promise((resolve) => {
    //perform some async actions
    resolve(result)
})

Then in components: 然后在组件中:

fetchData().then((result) => this.setState({msg: result})

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

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