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.
  1. import { BrowserRouter as Router, Route } from 'react-router-dom';
  2. const App = () => (
  3. <Router>
  4. #using exact prop to make the path exact match
  5. <Route path='/' exact component={Join} />
  6. <Route path='/room' component={Room} />
  7. <Route path='/chat' component={Chat} />
  8. </Router>
  9. );

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.

  1. import React from 'react'
  2. import ReactDOM from 'react-dom'
  3. const App = () => {
  4. const now = new Date()
  5. const a = 10
  6. const b = 20
  7. return React.createElement(
  8. 'div',
  9. null,
  10. React.createElement(
  11. 'p', null, 'Hello world, it is ', now.toString()
  12. ),
  13. React.createElement(
  14. 'p', null, a, ' plus ', b, ' is ', a + b
  15. )
  16. )
  17. }
  18. ReactDOM.render(
  19. 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]

  1. <a name="WXYj3"></a>
  2. ## React Reduce
  3. - **Sum all values of an array**
  4. - **Sum of values in an object array**
  5. - **Flatten an array of arrays**
  6. ```javascript
  7. let sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  8. return accumulator + currentValue
  9. }, 10)
  10. // sum = 10 + 0 + 1 + 2 + 3;

Important Points

  1. 注意⚠️:npm中的React包可能存在相互依赖的情况,容易导致invalid hook call