Initialization
Basic Router in React
- BrowserRouter: uses the HTML5 History API to keep your UI in sync with the URL
- Route: renders some UI if the current location matches the route’s path
- Link: navigate between pages. It’s comparable to the HTML anchor element. However, using anchor links would result in a full page refresh, which we don’t want. So instead, we can use to navigate to a particular URL and have the view re-rendered without a refresh.
import { BrowserRouter as Router, Route } from 'react-router-dom';const App = () => (<Router>#using exact prop to make the path exact match<Route path='/' exact component={Join} /><Route path='/room' component={Room} /><Route path='/chat' component={Chat} /></Router>);
How the React JSX is Compiled?
Although JSX looks like HTML, we are actually dealing with a way to write JavaScript. Under the hood, JSX returned by React components is compiled into JavaScript.
import React from 'react'import ReactDOM from 'react-dom'const App = () => {const now = new Date()const a = 10const b = 20return React.createElement('div',null,React.createElement('p', null, 'Hello world, it is ', now.toString()),React.createElement('p', null, a, ' plus ', b, ' is ', a + b))}ReactDOM.render(React.createElement(App, null), document.getElementById('root'))
React Map
- Creates a new array populated with the results of calling a provided function on every element in the calling array.
- Mapping an array of numbers to an array of square roots, e.g., Square Root Value
- Using map to reformat objects in an array
- Mapping an array of numbers using a function containing an argument ```javascript const array1 = [1, 4, 9, 16];
// pass a function to map const map1 = array1.map(x => x * 2);
console.log(map1); // expected output: Array [2, 8, 18, 32]
<a name="WXYj3"></a>## React Reduce- **Sum all values of an array**- **Sum of values in an object array**- **Flatten an array of arrays**```javascriptlet sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {return accumulator + currentValue}, 10)// sum = 10 + 0 + 1 + 2 + 3;
Important Points
- 注意⚠️:npm中的React包可能存在相互依赖的情况,容易导致invalid hook call
