The React Conf 2017 wrapped up at the Santa Clara Marriott Hotel in California, marking Facebook’s third official React conference. We couldn’t attend, but as front-end developers, we certainly couldn’t miss this great learning opportunity.

I took advantage of the Qingming Holiday to check out the record of the conference on YouTube. A total of 34 wonderful speeches, corresponding to 34 videos. Gain a lot.

Here, as a series, several of these speeches will be translated and analyzed. And auxiliary code demo, to help you understand.

Welcome to follow my simple book or gold digging account, also welcome to Github follow, the latest conference code demo, you can grasp the first time.

React + ES Next = ♥

Ben Ilegbodu was “one of the few” programmers of color at the conference. Black programmers are as rare as women. However, this topic is very loving, very nutritious, and not any less wonderful. React doesn’t matter if you don’t know how to React, because this is ES6 and ES7. Therefore, it is actually the popularization and introduction of the next generation of ES.

This article will be

  • Destructuring,
  • Spread Opetator,
  • Arrow’s Function,
  • Promises,
  • Async Functions

So these are going to unfold. And through nodeJS, a small “comment/message publishing reading system” with both front-end and back-end is realized.

Ben Ilegbodu -react + ES next = ♥ -React Conf 2017

Realize the preview

As shown, we have implemented the following page. This is a front-end + back-end full stack small project. Of course, the style is extremely rudimentary. As a “rough” programmer, I’m too lazy to spend time on pages.

es-next.png

We can enter the name and message content in the input box. And click the button to submit. NodeJS Express framework is used in the background to update files.

app.post('/api/comments'.function(req, res) {
    fs.readFile(COMMENTS_FILE, function(err, data) {
        if (err) {
            console.error(err);
            process.exit(1);
        }
        var comments = JSON.parse(data);
        var newComment = {
            id: Date.now(),
            author: req.body.author,
            text: req.body.text,
        };
        comments.push(newComment);
        fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null.4), function(err) {
            if (err) {
                console.error(err);
                process.exit(1);
            }
            res.json(comments);
        });
    });
});Copy the code

This is the back-end code for nodeJS, so don’t worry if you don’t understand it.

So let’s go back to the presentation.

Deconstruction Destructuring

In our project, the original version had this code:

_handleCommentSubmit(comment) {
    let comments = this.state.comments; .// remaining code
}Copy the code

Keep the _handleCommentSubmit function in mind, and the rest of the article will focus on it and expand step by step. The logic of this function is to process the newly submitted comment by first reading the existing Comments array from state. In the case of destructuring assignment, we refactor as:

_handleCommentSubmit(comment) {
    let {comments} = this.state; .// remaining code
}Copy the code

It may not be obvious how deconstruction works, but it is necessary when there is a lot of logic. Such as:

let author = this.state.author;
let text = this.state.text;Copy the code

Can be written as:

let {author, text} = this.state;Copy the code

If a variable name needs to be changed, it can be changed from:

let authorName = this.state.author;
let fullText = this.state.text;Copy the code

To:

let {author: authorName, text: fullText} = this.state;Copy the code

Here’s another example, in the case of function Component (a recommended form of the React stateless component) :

function MyComponent(props) {
    return (
        <div style={props.style}>{props.children}</div>
    )
}
<MyComponent style="dark">Stateless function! </MyComponent>Copy the code

We can rewrite it as:

function MyComponent({children, style}) {
    return (
        <div style={style}>{children}</div>
    )
}
<MyComponent style="dark">Stateless function! </MyComponent>Copy the code

Spread Opetator

Remember the _handleCommentSubmit function above? Now we’re going to expand. First we add a timestamp as id to the newly submitted comment (the function argument). Next, after we get the old state.comments, we need to add the new comment (including id) to the state.comments.

The first version is:

_handleCommentSubmit(comment) {
    let {comments} = this.state;
    let newComment = comment;

    newComment.id = Date.now();

    letnewComments = comments.concat([newComment]); .// setState + ajax stuffs
}Copy the code

After using the expansion, we can refactor to:

_handleCommentSubmit(comment) {
    let {comments} = this.state;
    letnewComment = {... comment,id: Date.now()};
    letnewComments = [...comments, newComment]; .// setState + ajax stuffs
}Copy the code

Of course, the expander has a lot of other benefits; For example, we can usually use the math. Max method to find the maximum value of an array:

var arrayOfValue = [33.2.9];
var maxValueFromArray = Math.max.apply(null, arrayOfValue)Copy the code

This idea takes advantage of apply’s ability to accept an array as a function parameter. Using the expansion, we can:

var arrayOfValue = [33.2.9];
var maxValueFromArray = Math.max(... arrayOfValue);Copy the code

Similarly, we can extend an array like this:

let values = [2.3.4];
let verbose = [1. values,5];Copy the code

Of course, this is all an expansion of an array.

The use of expanders for object attributes has also reached Stage3. In the future, we can write code like this:

let warriors = {Steph: 95.Klay: 82.Draymond: 79};
letnewWarriors = { ... warriors,Kevin: 97
}Copy the code

Instead of using object. assign to extend objects.

Arrow Function

The benefit of the arrow function is definitely the binding of this. Now go back to our _handleCommentSubmit function. With the initialization done, we need to send the new comment asynchronously to the back end via Ajax. In a successful callback, do setState processing:

$.ajax({
    url: this.props.url,
    data: comment,
    success: function(resJson) {
        this.setState({comments: resJson})
    }.bind(this)})Copy the code

Experienced students have noticed that I used bind to change the handling of this. Under the ES6 arrow function, we can directly:

$.ajax({
    url: this.props.url,
    data: comment,
    success: (resJson) = > {
        this.setState({comments: resJson})
    }
})Copy the code

Let’s expand the arrow function to see how it can be used:

  • Anonymous functions, single-argument cases, such as implementing the square of an array’s terms:
let squares = [1.2.3].map(value= > value * value);Copy the code
  • Anonymous functions, multi-argument cases, such as implementing the sum of the items in an array:
let sum = [9.8.7].reduce((prev, value) = > prev + value, 0)Copy the code

In this case, you need to put the parameters in parentheses.

  • Non-anonymous function, no return value case:
const alertUser = (message) = > {
    alert(message)
}Copy the code

At this point, the function body is enclosed in curly braces.

  • More complex cases, such as the one we used above:
const MyComponent = ({children, style}) = > (
    <div style={style}>{children}</div>
)Copy the code

Promises

The above code uses jquery’s Ajax method to send asynchronous requests, which can lead to “callback hell” in some cases. To do this, we use the fetch method, which is based on Promise, to refactor:

_handleCommentSubmit(comment) {
    // ...
    fetch(this.props.url, {
        method: 'POST'.body: Json.stringify(comment)
    })
        .then((res) = >res.json())
        .then((resJson) = >{
            this.setState({comments: resJson})
        })
        .catch((ex) = >{
            console.error(this.props.url, ex)
        })
}Copy the code

Of course, we can make the above code more abstract:

const fetchJson = (path, options) = > {
    fetch(`${DOMAIN}${path}`, options)
        .then((res) = >res.json())
}Copy the code

When we pull comments, we can:

const fetchComments = (a)= > fetchJson('api/comments')Copy the code

Fetch based on Promises makes asynchronous requests flexible and reliable.

At the same time, I amway a sleep function based on Promises:

const sleep = (delay = 0) = > {
    new Promise((resolve) = >{
        setTimeout(resolve, delay)
    })
}

sleep(3000)
    .then((a)= >getUniqueCommentAuthors())
    .then((uniqueAuthors) = >{this.state({uniqueAuthors})})Copy the code

Back in our Project, in the back-end nodeJS implementation, we store all comments in a data/comments.json file. When rendering a view, it is inevitable to read the data/comments.json file, which should also be done asynchronously:

const readFile = (filePath) = > (
    new Promise((resolve, reject) = >{
        fs.readFile(filePath, (err, data)=>{
            if (err) {reject(err)}
            resolve(data)
        })
    })
)

readFile('data/comments.json')
    .then((data) = >console.log('Here is the data', data))
    .catch((ex) = >console.log('Arg! ', ex))Copy the code

Async Functions

Promises have disadvantages, too.

A more advanced way is to use Async, back to our _handleCommentSubmit method, which we can refactor to:

async _handleCommentSubmit(comment) {
    try {
        let res = await fetch(this.props.url, {
            method: 'POST'.body: JSON.stringify(comment)
        });
        newComments = await res.json();
    }
    catch (ex) {
        console.error(this.props.url, ex);
        newComments = comments;
    }

    this.setState({comments: newComments});
}Copy the code

conclusion

The speech vividly illustrates how React fits seamlessly with ES Next. Whether React or ES, I believe that in the final analysis, they are all aimed at liberating productivity to a greater extent.

Readers are welcome to communicate with me and leave comments if you have any questions. There will be more fresh react Conf video translations available in the coming days.

Happy Coding!

PS: author Github warehouse, welcome to communicate through various forms of code.