简体   繁体   English

从ReactJS调用JavaScript函数

[英]Call javascript function from ReactJS

I am new to javascript and reactJS and I'm stuck. 我是javascript和reactJS的新手,我被卡住了。 I have a javascript file where I make a REST call. 我有一个javascript文件,我在其中进行REST调用。 The file looks like this: 该文件如下所示:

var data;
function getDataRequest() {
 const request = new XMLHttpRequest();
    request.open('GET', "localhost:8080/getData", true);
    request.onload = function () {
        var data = JSON.parse(this.response);
        if (request.status >= 200 && request.status < 400) {
            products = data;
        } else {
            console.log('error');
        }
    };
    request.send();
}
var getDataList = function() {
    getDataRequest();
    return data;
};
getDataList();

And the file which contains the React component looks like this: 包含React组件的文件如下所示:

var = data;
class Datas extends React.Component {

    render() {
        data = this.getDataList;
        return (
            <DataTable data={data} />
        );
    }
}
export default Products;

The problem is that data in the React component remains 'undefined'. 问题在于React组件中的数据保持“未定义”。 I am making the rest call in a different file because I want to call the rest call from multiple react components. 我要在其他文件中进行rest调用,因为我想从多个react组件调用rest调用。

You're grabbing data from the server in your render call, which is a really bad idea. 您在渲染调用中从服务器获取数据,这确实是个坏主意。 Use componentDidMount to load data, then store it in the state. 使用componentDidMount加载数据,然后将其存储在状态中。

First, here's you Data.js : 首先,这是您Data.js

export default {
  getDataList: () => fetch("//localhost:8080/getData").then(res => res.json())
};

In your Component, import Data from './Data'; 在您的组件中, import Data from './Data'; , then do this: ,然后执行以下操作:

componentDidMount = () => {  // using this syntax auto-binds 'this'
  Data.getDataList().then(res => {
    this.setState({ data: res });
  });
}

render() {
  return (
    <DataTable data={this.state.data} />
  );
}

You need to be aware of the React component lifecycle. 您需要了解React组件的生命周期。 In a nutshell, there are certain functions that React calls in a certain order. 简而言之,React会按特定顺序调用某些函数。 Some are called before the component is rendered and some are called after. 有些在组件呈现之前被调用,而有些则在组件呈现之后被调用。 In your case, you want to make an API call once the component is rendered. 对于您的情况,您希望在渲染组件后进行API调用。 An appropriate lifecycle method for this is componentDidMount . 合适的生命周期方法是componentDidMount Please see here for more detailed information about the component lifecycle methods. 请参阅此处以获取有关组件生命周期方法的更多详细信息。

Below is an example of this behaviour. 下面是这种行为的一个示例。 Note that I have used the fetch API instead of XmlHttpRequest. 请注意,我使用的是提取API而不是XmlHttpRequest。 It is much cleaner to work with and is part of JavaScript. 它使用起来更加简洁,并且是JavaScript的一部分。

class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loaded: false,
      something: ""
    };
  }

  componentDidMount() {
    fetch("exampleurl")
      .then(response => {
        return response.json();
      })
      .then(json => {
        // perform desired checks etc

        this.setState({
          something: json.someProperty
        });
      });
  }

  render() {
    if (!this.state.loaded) {
      return <div>{"Loading..."}</div>;
    }

    return <div>{this.state.something}</div>;
  }
}

export default Example;

You need to pass a callback to your generic function to be able to update the state 您需要将回调传递给泛型函数,以便能够更新状态

function getDataRequest(callback) { // here
    const request = new XMLHttpRequest();
    request.open('GET', "localhost:8080/getData", true);
    request.onload = function () {
        var data = JSON.parse(this.response);
        if (request.status >= 200 && request.status < 400) {
            callback(data) // here
        } else {
            console.log('error');
        }
    };
    request.send();
}

You need to create a state and trigger the call in the componentDidMount, after the first render. 在第一个渲染之后,您需要创建一个状态并在componentDidMount中触发调用。

export default class Datas extends React.Component {

    state = {
        data: null // or [] ?
    }

    componentDidMount(){
        const callback = (value) => {
            this.setState({
                data: value
            })
        }
        this.getDataList(callback);
    }

    render() {
        const {
            data
        } = this.state;

        return (
            <DataTable data={data} />
        );
    }
}

Firstly, there are no function getDataList in your React Component Datas . 首先,您的React Component Datas中没有函数getDataList Secondly, if you want to call getDataList from your React Componet, please export or make your function is global. 其次,如果您想从React Componet调用getDataList ,请导出或使您的函数成为全局函数。 You can use: 您可以使用:

window.getDataList = function() {
    getDataRequest();
    return data;
};

and in your React Component, you can call window.getDataList() easily. 在您的React组件中,您可以轻松地调用window.getDataList()

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

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