React-Request-Get-Initiate http Request

Index of React+Electron Desktop Application Development Articles

This article describes how to initiate http requests to get data from the server during the development of React Web sites.

Dead work

Install the superagent module, a tool to get get get data from the server or push data to the server by post ing it:

zhyuzh$ cnpm i superagent --save-dev

Official Open Source Project Address for superagent

Create a datas/mydata.js file in the dist directory to place the file instead of the number of json data returned by the server interface, so it's best to use a strict json format with double quotes for the field names and no commas after the last field:

    "title": "Heading 1",
    "text": "Text Content 1"
    "title": "Heading 2",
    "text": "Text Content 2"

Initiate get request

When an element is added to the page, make a request, noting that the data is converted using JSON here.

Once you have the data, you can use setState to make it work immediately.

Modified section in HomePage.js:

    componentDidMount() {
        let that = this
            .end((err, res) => {
                    mylist: JSON.parse(res.text)

In the render() method, if mylist data generation elements are used (for example, multiple duplicate interface elements are generated from a single list), setState automatically refreshes these elements when the data is read.

Like the following code:

let rightItems = []
        for (let i = 0; i < this.state.articleList.length; i++) {
            let data = this.state.articleList[i]
            rightItems.push(h(Grid, {
                item: true,
                xs: 12,
                sm: 6,
                md: 4,
                lg: 3,
            }, [
                h(Card, {
                    className: css.card
                }, h(CardContent, {}, [
                    h(CardMedia, {
                        image: data.image,
                        className: css.cardMedia
                    h(CardContent, {
                        style: {
                            padding: 0
                    }, data.title)

Committed to making everything simple

If you find an error in the article, please leave a message to correct it.
If you find it useful, please like it;
If you find it useful, please reload ~


Tags: JSON React

Posted on Thu, 12 Mar 2020 12:31:41 -0400 by castis