问题
When I googled about React.js what I got is: React.js is a Framework that is used to create user interfaces. If a particular part of the website is frequently updated that means we can use react. But I am confused that Ajax has been used for this only. We can update a part of site using Ajax without page refresh. For templating we would be using handlebars and mustache. Could somebody explain me in what ways react is different from Ajax and why we should use it.
回答1:
Ajax is used to refresh a web page without having to reload it : it sends a request to the server, but typically the response is processed by the javascript that displays dynamically a new element on the browser without having to reload the entire page.
React is a javascript library that dynamically update the page with inferface components. The components are calculated either by javascript interactions or by an ajax request that go through the server. So ReactJS can also use Ajax requests to update the page.
Mustache and Handlebars are a bit different from ReactJS as the main goal is to transform a template in a component that will be displayed in a page. It can also use Ajax to get data (for getting templates or json datas).
回答2:
This is probably a more simple explanation than you're looking for, but for anyone else who may be confused...
To understand React, you need to understand how AJAX changed everything:
Remember the internet in the 90's?
When you clicked anything, the page would have to reload to show you what happened with your click - even if it was nothing.
Here's an awesome example. Go to that page and click around... See how clicks whisk you away to a completely different page? That is the Internet before AJAX: Processing an action required loading new pages - even if it was the same page.
Now, take a look at this very page: next to each answer is an Up Arrow. Go ahead and click one of them. Notice the page doesn't reload, but you are given feedback: the arrow turns Orange. This may seem insignificant, but it represents big advancements in web technology.
A good analogy is a wrist-watch with hands that show hours, minutes and seconds. The hands seamlessly move around the clock face to show the time. But, what if every movement of the second hand caused the entire watch face to be destroyed and rebuilt? Well, that would be outrageous, right? That's a lot of wasted effort just to show basically the same thing. This is what the Internet was before AJAX: destroying an entire web page and rebuilding it to show basically the same thing. AJAX allows only that small change to be updated, while the rest of the page stays the same.
Everything else mentioned moving forward: React, Moustache, etc, and in fact most web technologies ever created in our lifetime is only there to make it easier to do this: make a small change and show it. It sounds simple, and it is, but the complexity comes with how many small things you need to change, which in application development very quickly becomes a lot.
But, to better explain, I'll walk through each technology you mentioned, and tell you how they work together to make real-time updating work.
AJAX
AJAX stands for Asynchronous Javascript And XML. Obviously, this is an outdated term because XML isn't used much these days to move data around. If AJAX was invented now, the X would be a J for JSON , which stands for JavaScript Object Notation (which is a fancy way of saying a simple JavaScript Object turned into a string), but AJAJ doesn't sound great so AJAX lingers.
Anyway, the basic premise here is a user performs an action, and the effect of that action is shown to the user - seamlessly - like the hands on our watch.
But let's break that process down using the action "clicking an up-arrow on this Stack Overflow page" as an example:
- The User clicks the Up Arrow
- This activates some JavaScript that was loaded with the page.
- Your browser (Chrome, IE, Firefox, etc), instructed by the javascript, sends a message to another computer - the Stack Overflow "server" (a server is a computer or service running on a computer whose job is to respond when contacted - they "serve" data and web page info as needed). AJAX allows this message to be sent without the page reloading. What is sent is known as a request, because your browser is requesting something from the server. What comes back from the server is a response.
- The Stack Overflow server uses business logic (non-coding rules that govern how applications behaves) in the "server-side" code (code that lives on the server instead of being loaded into your browser) to confirm that you are allowed to click the arrow (an example of not being allowed would be to upvote when you're not logged in).
- The SO server sends a message to your browser (the response) saying basically "yes" or "no".
The message that comes back is probably in JSON format, and would look something like this (but much more complex):
{ "action": "upvote", "success": "true" }
If SO used XML to express data instead, it would look more like this:
<xml>
<action>upvote</action>
<success>true</success>
</xml>
If SO was using such an environment React, Mustache and Handlebars would understand this response and work together to make the arrow orange. But if all the site did was change arrow colors you wouldn't need any of these things, you can do everything in JavaScript. But as application complexity grows - which applications desperately want to do - the need for more complex JS libraries becomes more real, and you'll wish you had used one.
Everything nowadays uses AJAX. It's hard to imagine the web without it, and as a developer it's becoming increasingly easier to write a web application without even knowing what AJAX is. This is because it has become assimilated into the javaScript technologies we use, like React - which uses fetch in place of XMLHttpRequest (The JavaScript way of making an asynchronous request) or $.ajax, $.get, or $.post (the JQuery ways).
Single-Page Applications
Single-page applications load all the HTML, CSS, and JavaScript up front. Then, as the user interacts with the site, different parts of the HTML and CSS get used. it's also likely the HTML will change to show changing values received from the user or the server. For instance, Stack Overflow is considered a single-page application, and clicking an Up Arrow is an example of both user interaction and server response:
When you upvote, the server isn't sending a whole new page with an orange arrow, it's not even sending a brand new orange arrow, it's sending a "Yes." That "Yes" via the JavaScript changes the HTML - it adds a new class to the arrow element. That CSS class has been available the whole time, it just wasn't on the HTML element yet. In React, you "bind" the arrow to a representation of that arrow in your code, so when a response changes its value, React automatically makes the changes necessary to the HTML element.
Anyway, this is the pivotal idea of modern web applications: You load everything up front, so as the user interacts with your site, it's fast and responsive. This is also a pillar of what's known as "Web 2.0" which basically means users actively participate in building the site instead of passively digesting content. Again, think about the Bill Gates site vs Stack Overflow. You can post questions and answers on Stack Overflow, participating in content creation, whereas the Bill Gates site was totally written by other people and you and I can only read what they wrote.
React.js
React is a javascript library for building Single-Page Applications. But so is Vue, Angular, and probably many more, so what's the big deal? Without getting into too much detail, they all help you, the developer, deal with user actions and using AJAX to interact with the server, but more importantly how those interactions change the HTML.
If you want to know which I would recommend for someone starting out? I say Vue2 by a mile.
But this is about React. So the user clicks the up arrow. AJAX goes between the browser and server to verify the user is allowed to click, then when the CSS class needs to be added to the HTML, what happens?
Basically React decides for you how to change the color of the arrow.
Browsers build a model of the HTML, but in simpler terms, so instead of <button type="text" class="btn"><i class="arrow"></button>
, it'll look something like {button:{type:"text",class:"btn",children:{i:{class:"arrow"}}}
. It does this for all your page's HTML elements. This is called the DOM (Document Object Model). JavaScript is the defacto language most browsers use to allow interaction with the DOM.
React creates a copy of the DOM, called a Virtual DOM (VDOM). When you make changes with React, you're actually changing the VDOM with simplified instructions that hide a lot of the complexity of the actual JS. Then, React updates the real DOM to reflect the VDOM.
"Why?" you say? because it's much easier to do this than to do what Angular does which is build new instructions directly into the DOM. This is also why Angular is a framework and React is a Library.
Mustache
Mustache is a templating system. Which means you can separate content and structure of a web page. For instance, here's a regular HTML page without Mustache:
<h1>This is the Title of My Page. This is Content</h1>
<p>This is a paragraph. blah blah blah. My email is me@me.com</p>
<footer>Contact me at me@me.com</footer>
The structure is defined by HTML. <h1>
and <p>
are "tags" that tell the browser (Chrome or Firefox or IE) how content is divided into sections.
Suppose you wanted to change your email address. You would have to change it in two places. This is bad, because maybe ten years goes by and you forget all the places you put your email, or someone else works on it, and they don't know it's in 2 places, so they change one place but not the other, then you might have customers emailing the wrong address. That can cost you money.
Mustache aims to fix this (among other things) by allowing you to use variables to display content in HTML. In mustache you can do something like this:
<script>
var json = {
title: "This is the Title of My Page. This is Content",
paragraph: "This is a paragraph. blah blah blah. My email is ",
footer_verbiage: "Contact me at ",
email: "me@me.com"
}
</script>
<h1>{{title}}</h1>
<p>{{paragraph}} {{email}}</p>
<footer>{{footer_verbiage}} {{email}}</footer>
See, you are defining the content in a script, separate from the structure. So if you wanted to change your email, you'd only have to change it in one place and it would propagate to all the places you want your email to show up.
Just like AJAX, this way of doing things was so pivotal for its time, that it now is incorporated in more modern js libraries. Pretty soon you'll be able to go your whole career without knowing about Mustache, but use it every day.
In fact, Angular and Vue use a similar templating system, double curly braces and all, but with no mention of Mustache - its just built in because its so logical. It's also familiar to veteran coders and easy to learn for newcomers - you don't have to learn a different templating system depending on the library. Angular and Vue will be relevant longer because they incorporated Mustache into their libraries.
Back to our grandfather clock example - mustache would be the hands of the clock. The hands take the shape of the data fed to them from being the scenes.
Handlebars
Handlebars makes Mustache more powerful. Here's a good post for more info on the differences. In our example above, Handlebars would allow the template (the HTML) to be re-rendered on the client (your browser) instead of the server. So, if your AJAX changed some content, it could show up live in the HTML.
Again, Handlebars was so revolutionary that it got built into newer things automatically. This is the pattern, and why learning these things is almost like learning history at this point because web application technology is moving so quickly and cannibalizes so ravenously.
In our grandfather clock example Handlebars would allow for a second hand to move seamlessly instead of ticking around the clock face. Without mustache the server would build the next thing you see, and send it to the client, and only then you could see it.
For example, if you log out of SO, then try to upvote something, pay close attention to the Up Arrow, for a moment it will turn orange before it reverts back to gray and asks you to login. This is because there's logic on your computer that reacts to a click and instructs the arrow to orange immediately instead of waiting for an "ok" from the server to do so.
Tying it all together
As we saw earlier, a webpage in the 90's was not able to change seamlessly - you'd have to wait for data to be sent to the server, and the server would send back a new html page. That is a "Static" web page. Our first code example is static because the content couldn't change without developer intervention.
The second example however, is a dynamic web page because the content is defined by the json
variable. Yes, the json
variable is defined on the same page (which means it's still a static page), but if it was instead defined by an ajax funciton, it could change whenever. This is what a basic AJAX function looks like:
AJAX.get("http://stackoverflow.api.com?upvote", function(response){
json = response.data;
});
you can see we have a url we are calling, and a function that says what to do with the response.
React would build the AJAX above and facilitate quicker development of a single-page application than without it, Mustache would allow content to be defined outside the webpage, and Handlebars would change that webpage on the client (a web browser) when the data comes back from the server.
Bonus - What is Angular? Why is it such a big deal?:
In the "tying it all together" section above, all that stuff that takes at least 3 javascript libraries to accomplish, Angular does all by itself, with less code and is easier to read (although it has drawbacks).
MVC stands for Model, View, Controller. It's a coding pattern that allows Web Applications to avoid complexity (see "spaghetti code"). If you've ever written an app in pure jquery, you know things can get out of hand really quickly. React, mustache and handlebars together set up this sort of paradigm.
Enter Angular
Angular allows you to do all this with one framework. In our examples above, you could change your email, and see it change live on the web page. This makes Angular a game-changer, being simple to learn the basics, but also allows for a lot of complexity.
As we've seen before, it's probably just a matter of time before another framework is released that encompasses all the greatness of Angular, but rids it of a lot of drawbacks. In fact, Vue combines popular components of Angular and React, and works quicker than either. As of now the Vue community is small, but it is growing rapidly.
Summary:
React is to AJAX as an airplane is to its wheels - the wheels are necessary for the plane to work, but aren't the first thing you think about when you think about a plane - so they're not really comparable. The wheels are part of the plane, and so is AJAX to React - AJAX is part of React.
I recommend checking out an online course to get up to speed on this stuff. I used udemy to learn about Typescript, and thought the class was good. But I also found some real stinkers on there, so be sure to read reviews. I have not been paid by udemy to say this, but if they want to pay me, I'd be grateful.
回答3:
To simply put, React is a JavaScript library built by Facebook. It is commonly looked as a framework because of its many extensions but the official docs label it as a library for building user interfaces. Ajax on the other hand is not a library or a framework or a language at all. Ajax is a technique used by programmers to call web APIs without having the flow of your code be interrupted at all. At the end of that day, your JavaScript code is run synchronously line by line and Ajax is run asynchronously within your synchronous code but in a way in which it will never pause your code from and have it wait for the API call to be sent and received. With Ajax, sending and receiving data is all done in the background so you won't have to worry about the delay that it takes to get that data. You can actually use Ajax in your React code. Ajax uses something called Fetch to actually call an API and you can use a variety of methods to handle the data that you receive from the API such as .then and .catch or Async/Await. You also aren't required to use Fetch at all, there are other third party ways of calling an API with Ajax such as by using Axios. I'd advise you to watch a video on how to use these different tools because when you figure out how they all work, you'll find that React and Ajax can be used together to build a great application. Hope this helped, please vote however way you felt about this answer. I'm pretty new to this website.
回答4:
just to clarify react is not a framework, it's a library!
take it from the horse's mouth:
https://facebook.github.io/react/
回答5:
Ajax
We are using ajax to send http requests. And we can't re-render a particular area of the page(DOM) by using ajax alone. We need jquery to re-render the page after an ajax call came up with the respond. Actually comparing jquery+HTML and React.js far better than comparing ajax and React.js.
React.js
The role of the react.js is dividing page(DOM) into small peaces(Components). ex:- Profile image area, Main Navigation, Sidebar, Textfield, Button. etc. from Big peaces to small peaces. Most importantly we can bind functionalities into these components. Ex:- Let's assume users need a popup to upload a profile image by clicking on above "Profile image area". We can write a function to open a popup. And also we can write another function to upload profile image to the database. In this way we can use ajax inside the React.js
Please follow this tutorial.
来源:https://stackoverflow.com/questions/35643991/difference-between-react-js-and-ajax