react 示例
I've put together for you an entire visual cheatsheet of all of the concepts and skills you need to master React in 2020.
我為您匯總了2020年掌握React所需的所有概念和技能的完整視覺摘要。
But don't let the label 'cheatsheet' fool you. This is more than a mere summary of React's features.
但不要讓標簽“備忘單”蒙騙您。 這不僅僅是React功能的總結。
My aim here was to clearly and concisely put forth the knowledge and patterns I've gained through working with React as a professional developer.
我的目的是清楚,簡潔地提出通過與React作為專業開發人員合作而獲得的知識和模式。
Each part is designed to be immensely helpful by showing you real-world, practical examples with meaningful comments to guide you along the way.
通過向您展示真實實用的示例以及有意義的注釋來指導您的工作,每個部分都將為您提供極大的幫助。
想要自己的副本? 📄 (Want Your Own Copy? 📄)
Grab the PDF cheatsheet right here (it takes 5 seconds).
在此處獲取PDF速查表(需要5秒鐘)。
Here are some quick wins from grabbing the downloadable version:
從下載可下載版本中可以快速獲得一些好處:
- ? Quick reference guide to review however and whenever ?快速參考指南,可隨時隨地進行審核
- ? Tons of copyable code snippets for easy reuse ?大量可復制的代碼片段,易于重用
- ? Read this massive guide wherever suits you best. On the train, at your desk, standing in line... anywhere. ?閱讀最適合您的詳細指南。 在火車上,在您的辦公桌前,在任何地方排隊。
Note: There is limited coverage of class components in this cheatsheet. Class components are still valuable to know for existing React projects, but since the arrival of Hooks in 2018, we are able to make our apps with function components alone. I wanted to give beginners and experienced developers alike a Hooks-first approach treatment of React.
注意:本備忘單中類組件的覆蓋范圍有限。 對于現有的React項目,類組件仍然是有價值的知識,但是自從Hooks在2018年問世以來,我們就能夠使我們的應用程序僅包含功能組件。 我想給初學者和經驗豐富的開發人員一樣對Hooks的Hooks優先方法的對待。
There's a ton of great stuff to cover, so let's get started.
有很多很棒的東西要介紹,所以讓我們開始吧。
目錄 (Table of Contents)
核心概念 (Core Concepts)
- Elements and JS 元素和JS
- Components and Props 組件和道具
- Lists and Keys 列表和鍵
- Events and Event Handlers 事件和事件處理程序
React鉤 (React Hooks)
- State and useState 狀態和使用狀態
- Side Effects and useEffect 副作用和使用效果
- Performance and useCallback 性能和使用回調
- Memoization and useMemo 備注和使用備注
- Refs and useRef 參考和使用參考
高級掛鉤 (Advanced Hooks)
- Context and useContext 上下文和useContext
- Reducers and useReducer 減速器及使用
- Writing custom hooks 編寫自定義鉤子
- Rules of hooks 鉤子規則
核心概念 (Core Concepts)
Elements和JSX (Elements and JSX)
This is the basic syntax for a React element:
這是React元素的基本語法:
// In a nutshell, JSX allows us to write HTML in our JS
// JSX can use any valid html tags (i.e. div/span, h1-h6, form/input, etc)
<div>Hello React</div>
JSX elements are expressions:
JSX元素是表達式:
// as an expression, JSX can be assigned to variables...
const greeting = <div>Hello React</div>;const isNewToReact = true;// ... or can be displayed conditionally
function sayGreeting() {if (isNewToReact) {// ... or returned from functions, etc.return greeting; // displays: Hello React} else {return <div>Hi again, React</div>;}
}
JSX allows us to nest expressions:
JSX允許我們嵌套表達式:
const year = 2020;
// we can insert primitive JS values in curly braces: {}
const greeting = <div>Hello React in {year}</div>;
// trying to insert objects will result in an error
JSX allows us to nest elements:
JSX允許我們嵌套元素:
// to write JSX on multiple lines, wrap in parentheses: ()
const greeting = (// div is the parent element<div>{/* h1 and p are child elements */}<h1>Hello!</h1><p>Welcome to React</p></div>
);
// 'parents' and 'children' are how we describe JSX elements in relation
// to one another, like we would talk about HTML elements
HTML and JSX have a slightly different syntax:
HTML和JSX的語法略有不同:
// Empty div is not <div></div> (HTML), but <div/> (JSX)
<div/>// A single tag element like input is not <input> (HTML), but <input/> (JSX)
<input name="email" />// Attributes are written in camelcase for JSX (like JS variables
<button className="submit-button">Submit</button> // not 'class' (HTML)
The most basic React app requires three things:
最基本的React應用程序需要三件事:
- ReactDOM.render() to render our app ReactDOM.render()渲染我們的應用
- A JSX element (called a root node in this context) JSX元素(在此上下文中稱為根節點)
- A DOM element within which to mount the app (usually a div with an id of root in an index.html file) 一個要在其中安裝應用程序的DOM元素(通常是index.html文件中ID為root的div)
// imports needed if using NPM package; not if from CDN links
import React from "react";
import ReactDOM from "react-dom";const greeting = <h1>Hello React</h1>;// ReactDOM.render(root node, mounting point)
ReactDOM.render(greeting, document.getElementById("root"));
組件和道具 (Components and Props)
This is the syntax for a basic React component:
這是基本的React組件的語法:
import React from "react";// 1st component type: function component
function Header() {// function components must be capitalized unlike normal JS functions// note the capitalized name here: 'Header'return <h1>Hello React</h1>;
}// function components with arrow functions are also valid
const Header = () => <h1>Hello React</h1>;// 2nd component type: class component
// (classes are another type of function)
class Header extends React.Component {// class components have more boilerplate (with extends and render method)render() {return <h1>Hello React</h1>;}
}
This is how components are used:
這是組件的使用方式:
// do we call these function components like normal functions?// No, to execute them and display the JSX they return...
const Header = () => <h1>Hello React</h1>;// ...we use them as 'custom' JSX elements
ReactDOM.render(<Header />, document.getElementById("root"));
// renders: <h1>Hello React</h1>
Components can be reused across our app:
組件可以在我們的應用程序中重復使用:
// for example, this Header component can be reused in any app page// this component shown for the '/' route
function IndexPage() {return (<div><Header /><Hero /><Footer /></div>);
}// shown for the '/about' route
function AboutPage() {return (<div><Header /><About /><Testimonials /><Footer /></div>);
}
Data can be dynamically passed to components with props:
數據可以通過props動態傳遞給組件:
// What if we want to pass data to our component from a parent?
// I.e. to pass a user's name to display in our Header?const username = "John";// we add custom 'attributes' called props
ReactDOM.render(<Header username={username} />,document.getElementById("root")
);
// we called this prop 'username', but can use any valid JS identifier// props is the object that every component receives as an argument
function Header(props) {// the props we make on the component (i.e. username)// become properties on the props objectreturn <h1>Hello {props.username}</h1>;
}
Props must never be directly changed (mutated):
道具絕不能直接更改(變異):
// Components must ideally be 'pure' functions.
// That is, for every input, we be able to expect the same output// we cannot do the following with props:
function Header(props) {// we cannot mutate the props object, we can only read from itprops.username = "Doug";return <h1>Hello {props.username}</h1>;
}
// But what if we want to modify a prop value that comes in?
// That's where we would use state (see the useState section)
Children props are useful if we want to pass elements / components as props to other components.
如果我們想將元素/組件作為道具傳遞給其他組件,則子道具很有用。
// Can we accept React elements (or components) as props?
// Yes, through a special property on the props object called 'children'function Layout(props) {return <div className="container">{props.children}</div>;
}// The children prop is very useful for when you want the same
// component (such as a Layout component) to wrap all other components:
function IndexPage() {return (<Layout><Header /><Hero /><Footer /></Layout>);
}// different page, but uses same Layout component (thanks to children prop)
function AboutPage() {return (<Layout><About /><Footer /></Layout>);
}
Conditionally displaying components with ternaries and short-circuiting:
有條件地顯示具有三元和短路的組件:
// if-statements are fine to conditionally show , however...
// ...only ternaries (seen below) allow us to insert these conditionals
// in JSX, however
function Header() {const isAuthenticated = checkAuth();return (<nav><Logo />{/* if isAuth is true, show AuthLinks. If false, Login */}{isAuthenticated ? <AuthLinks /> : <Login />}{/* if isAuth is true, show Greeting. If false, nothing. */}{isAuthenticated && <Greeting />}</nav>);
}
Fragments are special components for displaying multiple components without adding an extra element to the DOM.
片段是特殊的組件,用于顯示多個組件,而無需向DOM添加額外的元素。
Fragments are ideal for conditional logic:
片段是條件邏輯的理想選擇:
// we can improve the logic in the previous example
// if isAuthenticated is true, how do we display both AuthLinks and Greeting?
function Header() {const isAuthenticated = checkAuth();return (<nav><Logo />{/* we can render both components with a fragment */}{/* fragments are very concise: <> </> */}{isAuthenticated ? (<><AuthLinks /><Greeting /></>) : (<Login />)}</nav>);
}
列表和鍵 (Lists and Keys)
Use .map() to convert lists of data (arrays) into lists of elements:
使用.map()將數據(數組)列表轉換為元素列表:
const people = ["John", "Bob", "Fred"];
const peopleList = people.map(person => <p>{person}</p>);
.map() is also used for components as well as elements:
.map()也用于組件和元素:
function App() {const people = ['John', 'Bob', 'Fred'];// can interpolate returned list of elements in {}return (<ul>{/* we're passing each array element as props */}{people.map(person => <Person name={person} />}</ul>);
}function Person({ name }) {// gets 'name' prop using object destructuringreturn <p>this person's name is: {name}</p>;
}
Each React element iterated over needs a special 'key' prop. Keys are essential for React to be able to keep track of each element that is being iterated over with map
每個迭代的React元素都需要一個特殊的“關鍵”道具。 密鑰對于React至關重要,以便能夠跟蹤正在被map迭代的每個元素
Without keys, it is harder for it to figure out how elements should be updated when data changes.
如果沒有鍵,則很難確定在數據更改時應如何更新元素。
Keys should be unique values to represent the fact that these elements are separate from one another.
鍵應該是唯一的值,以表示這些元素彼此分開的事實。
function App() {const people = ['John', 'Bob', 'Fred'];return (<ul>{/* keys need to be primitive values, ideally a generated id */}{people.map(person => <Person key={person} name={person} />)}</ul>);
}// If you don't have ids with your set of data or unique primitive values,
// you can use the second parameter of .map() to get each elements index
function App() {const people = ['John', 'Bob', 'Fred'];return (<ul>{/* use array element index for key */}{people.map((person, i) => <Person key={i} name={person} />)}</ul>);
}
事件和事件處理程序 (Events and Event Handlers)
Events in React and HTML are slightly different.
React和HTML中的事件略有不同。
// Note: most event handler functions start with 'handle'
function handleToggleTheme() {// code to toggle app theme
}// in html, onclick is all lowercase
<button onclick="handleToggleTheme()">Submit
</button>// in JSX, onClick is camelcase, like attributes / props
// we also pass a reference to the function with curly braces
<button onClick={handleToggleTheme}>Submit
</button>
The most essential React events to know are onClick and onChange.
要了解的最重要的React事件是onClick和onChange。
- onClick handles click events on JSX elements (namely buttons) onClick處理JSX元素(即按鈕)上的點擊事件
- onChange handles keyboard events (namely inputs) onChange處理鍵盤事件(即輸入)
function App() {function handleChange(event) {// when passing the function to an event handler, like onChange// we get access to data about the event (an object)const inputText = event.target.value;const inputName = event.target.name; // myInput// we get the text typed in and other data from event.target}function handleSubmit() {// on click doesn't usually need event data}return (<div><input type="text" name="myInput" onChange={handleChange} /><button onClick={handleSubmit}>Submit</button></div>);
}
React鉤 (React Hooks)
狀態和使用狀態 (State and useState)
useState gives us local state in a function component:
useState在函數組件中為我們提供本地狀態:
import React from 'react';// create state variable
// syntax: const [stateVariable] = React.useState(defaultValue);
function App() {const [language] = React.useState('javascript');// we use array destructuring to declare state variablereturn <div>I am learning {language}</div>;
}
Note: Any hook in this section is from the React package and can be imported individually.
注意:本節中的任何鉤子都來自React包,可以單獨導入。
import React, { useState } from "react";function App() {const [language] = useState("javascript");return <div>I am learning {language}</div>;
}
useState also gives us a 'setter' function to update the state it creates:
useState還為我們提供了一個“設置器”功能來更新其創建的狀態:
function App() {// the setter function is always the second destructured valueconst [language, setLanguage] = React.useState("python");// the convention for the setter name is 'setStateVariable'return (<div>{/* why use an arrow function here instead onClick={setterFn()} ? */}<button onClick={() => setLanguage("javascript")}>Change language to JS</button>{/* if not, setLanguage would be called immediately and not on click */}<p>I am now learning {language}</p></div>);
}// note that whenever the setter function is called, the state updates,
// and the App component re-renders to display the new state
useState can be used once or multiple times within a single component:
useState可以在單個組件中使用一次或多次:
function App() {const [language, setLanguage] = React.useState("python");const [yearsExperience, setYearsExperience] = React.useState(0);return (<div><button onClick={() => setLanguage("javascript")}>Change language to JS</button><inputtype="number"value={yearsExperience}onChange={event => setYearsExperience(event.target.value)}/><p>I am now learning {language}</p><p>I have {yearsExperience} years of experience</p></div>);
}
useState can accept primitive or object values to manage state:
useState可以接受原始值或對象值來管理狀態:
// we have the option to organize state using whatever is the
// most appropriate data type, according to the data we're tracking
function App() {const [developer, setDeveloper] = React.useState({language: "",yearsExperience: 0});function handleChangeYearsExperience(event) {const years = event.target.value;// we must pass in the previous state object we had with the spread operatorsetDeveloper({ ...developer, yearsExperience: years });}return (<div>{/* no need to get prev state here; we are replacing the entire object */}<buttononClick={() =>setDeveloper({language: "javascript",yearsExperience: 0})}>Change language to JS</button>{/* we can also pass a reference to the function */}<inputtype="number"value={developer.yearsExperience}onChange={handleChangeYearsExperience}/><p>I am now learning {developer.language}</p><p>I have {developer.yearsExperience} years of experience</p></div>);
}
If the new state depends on the previous state, to guarantee that the update is done reliably, we can use a function within the setter function that gives us the correct previous state.
如果新狀態依賴于先前狀態,則為保證可靠地完成更新,我們可以在setter函數中使用一個函數,該函數為我們提供正確的先前狀態。
function App() {const [developer, setDeveloper] = React.useState({language: "",yearsExperience: 0,isEmployed: false});function handleToggleEmployment(event) {// we get the previous state variable's value in the parameters// we can name 'prevState' however we likesetDeveloper(prevState => {return { ...prevState, isEmployed: !prevState.isEmployed };// it is essential to return the new state from this function});}return (<button onClick={handleToggleEmployment}>Toggle Employment Status</button>);
}
副作用和使用效果 (Side effects and useEffect)
useEffect lets us perform side effects in function components. So what are side effects?
useEffect讓我們在功能組件中執行副作用。 那么什么是副作用呢?
- Side effects are where we need to reach into the outside world. For example, fetching data from an API or working with the DOM. 副作用是我們需要接觸外界的地方。 例如,從API提取數據或使用DOM。
- Side effects are actions that can change our component state in an unpredictable fashion (that have caused 'side effects'). 副作用是可以以不可預測的方式更改組件狀態的動作(已引起“副作用”)。
useEffect accepts a callback function (called the 'effect' function), which will by default run every time there is a re-render. It runs once our component mounts, which is the right time to perform a side effect in the component lifecycle.
useEffect接受一個回調函數(稱為“效果”函數),默認情況下,它將在每次重新渲染時運行。 一旦我們的組件安裝好,它就會運行,這是在組件生命周期中產生副作用的正確時機。
// what does our code do? Picks a color from the colors array
// and makes it the background color
function App() {const [colorIndex, setColorIndex] = React.useState(0);const colors = ["blue", "green", "red", "orange"];// we are performing a 'side effect' since we are working with an API// we are working with the DOM, a browser API outside of ReactuseEffect(() => {document.body.style.backgroundColor = colors[colorIndex];});// whenever state is updated, App re-renders and useEffect runsfunction handleChangeIndex() {const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1;setColorIndex(next);}return <button onClick={handleChangeIndex}>Change background color</button>;
}
To avoid executing the effect callback after each render, we provide a second argument, an empty array:
為了避免在每次渲染后執行效果回調,我們提供了第二個參數,一個空數組:
function App() {...// now our button doesn't work no matter how many times we click it...useEffect(() => {document.body.style.backgroundColor = colors[colorIndex];}, []);// the background color is only set once, upon mount// how do we not have the effect function run for every state update...// but still have it work whenever the button is clicked?return (<button onClick={handleChangeIndex}>Change background color</button>);
}
useEffect lets us conditionally perform effects with the dependencies array.
useEffect讓我們有條件地執行依賴關系數組的效果。
The dependencies array is the second argument, and if any one of the values in the array changes, the effect function runs again.
依賴項數組是第二個參數,如果數組中的任何值發生更改,效果函數都會再次運行。
function App() {const [colorIndex, setColorIndex] = React.useState(0);const colors = ["blue", "green", "red", "orange"];// we add colorIndex to our dependencies array// when colorIndex changes, useEffect will execute the effect fn againuseEffect(() => {document.body.style.backgroundColor = colors[colorIndex];// when we use useEffect, we must think about what state values// we want our side effect to sync with}, [colorIndex]);function handleChangeIndex() {const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1;setColorIndex(next);}return <button onClick={handleChangeIndex}>Change background color</button>;
}
useEffect lets us unsubscribe from certain effects by returning a function at the end:
useEffect讓我們通過在最后返回一個函數來取消訂閱某些效果:
function MouseTracker() {const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });React.useEffect(() => {// .addEventListener() sets up an active listener...window.addEventListener("mousemove", event => {const { pageX, pageY } = event;setMousePosition({ x: pageX, y: pageY });});// ...so when we navigate away from this page, it needs to be// removed to stop listening. Otherwise, it will try to set// state in a component that doesn't exist (causing an error)// We unsubscribe any subscriptions / listeners w/ this 'cleanup function'return () => {window.removeEventListener("mousemove", event => {const { pageX, pageY } = event;setMousePosition({ x: pageX, y: pageY });});};}, []);return (<div><h1>The current mouse position is:</h1><p>X: {mousePosition.x}, Y: {mousePosition.y}</p></div>);
}// Note: we could extract the reused logic in the callbacks to
// their own function, but I believe this is more readable
- Fetching data with useEffect 使用useEffect獲取數據
Note that handling promises with the more concise async/await syntax requires creating a separate function. (Why? The effect callback function cannot be async.)
請注意,使用更簡潔的async / await語法處理Promise需要創建一個單獨的函數。 (為什么?效果回調函數不能異步。)
const endpoint = "https://api.github.com/users/codeartistryio";// with promises:
function App() {const [user, setUser] = React.useState(null);React.useEffect(() => {// promises work in callbackfetch(endpoint).then(response => response.json()).then(data => setUser(data));}, []);
}// with async / await syntax for promise:
function App() {const [user, setUser] = React.useState(null);// cannot make useEffect callback function asyncReact.useEffect(() => {getUser();}, []);// instead, use async / await in separate function, then call// function back in useEffectasync function getUser() {const response = await fetch("https://api.github.com/codeartistryio");const data = await response.json();setUser(data);}
}
性能和使用回調 (Performance and useCallback)
useCallback is a hook that is used for improving our component's performance.
useCallback是一個掛鉤,用于提高組件的性能。
If you have a component that re-renders frequently, useCallback prevents callback functions within the component from being recreated every single time the component re-renders (which means the function component re-runs).
如果您有一個頻繁重新渲染的組件,則useCallback防止在每次重新渲染組件時重新創建該組件內的回調函數(這意味著該函數組件重新運行)。
useCallback re-runs only when one of it's dependencies changes.
useCallback僅在其中一項依賴項更改時才重新運行。
// in Timer, we are calculating the date and putting it in state a lot
// this results in a re-render for every state update// we had a function handleIncrementCount to increment the state 'count'...
function Timer() {const [time, setTime] = React.useState();const [count, setCount] = React.useState(0);// ... but unless we wrap it in useCallback, the function is// recreated for every single re-render (bad performance hit)// useCallback hook returns a callback that isn't recreated every timeconst inc = React.useCallback(function handleIncrementCount() {setCount(prevCount => prevCount + 1);},// useCallback accepts a second arg of a dependencies array like useEffect// useCallback will only run if any dependency changes (here it's 'setCount')[setCount]);React.useEffect(() => {const timeout = setTimeout(() => {const currentTime = JSON.stringify(new Date(Date.now()));setTime(currentTime);}, 300);return () => {clearTimeout(timeout);};}, [time]);return (<div><p>The current time is: {time}</p><p>Count: {count}</p><button onClick={inc}>+</button></div>);
}
備注和使用備注 (Memoization and useMemo)
useMemo is very similar to useCallback and is for improving performance. But instead of being for callbacks, it is for storing the results of expensive calculations.
useMemo與useCallback非常相似,用于提高性能。 但是,它不是用于回調,而是用于存儲昂貴的計算結果。
useMemo allows us to 'memoize', or remember the result of expensive calculations when they have already been made for certain inputs (we already did it once for these values, so it's nothing new to do it again).
useMemo允許我們“記憶”,或記住已經為某些輸入進行了昂貴的計算的結果(我們已經對這些值進行了一次,因此再做一次并不是什么新鮮事)。
useMemo returns a value from the computation, not a callback function (but can be a function).
useMemo從計算中返回一個值,而不是回調函數(但可以是一個函數)。
// useMemo is useful when we need a lot of computing resources
// to perform an operation, but don't want to repeat it on each re-renderfunction App() {// state to select a word in 'words' array belowconst [wordIndex, setWordIndex] = useState(0);// state for counterconst [count, setCount] = useState(0);// words we'll use to calculate letter countconst words = ["i", "am", "learning", "react"];const word = words[wordIndex];function getLetterCount(word) {// we mimic expensive calculation with a very long (unnecessary) looplet i = 0;while (i < 1000000) i++;return word.length;}// Memoize expensive function to return previous value if input was the same// only perform calculation if new word without a cached valueconst letterCount = React.useMemo(() => getLetterCount(word), [word]);// if calculation was done without useMemo, like so:// const letterCount = getLetterCount(word);// there would be a delay in updating the counter// we would have to wait for the expensive function to finishfunction handleChangeIndex() {// flip from one word in the array to the nextconst next = wordIndex + 1 === words.length ? 0 : wordIndex + 1;setWordIndex(next);}return (<div><p>{word} has {letterCount} letters</p><button onClick={handleChangeIndex}>Next word</button><p>Counter: {count}</p><button onClick={() => setCount(count + 1)}>+</button></div>);
}
參考和使用參考 (Refs and useRef)
Refs are a special attribute that are available on all React components. They allow us to create a reference to a given element / component when the component mounts
引用是一個特殊屬性,可在所有React組件上使用。 它們允許我們在安裝組件時創建對給定元素/組件的引用
useRef allows us to easily use React refs. We call useRef (at the top of the component) and attach the returned value to the element's ref attribute to refer to it.
useRef允許我們輕松使用React refs。 我們調用useRef(在組件頂部),并將返回的值附加到元素的ref屬性以引用它。
Once we create a reference, we use the current property to modify (mutate) the element's properties. Or we can call any available methods on that element (like .focus() to focus an input).
創建引用后,我們將使用當前屬性來修改(變異)元素的屬性。 或者,我們可以在該元素上調用任何可用的方法(例如.focus()來使輸入集中)。
function App() {const [query, setQuery] = React.useState("react hooks");// we can pass useRef a default value// we don't need it here, so we pass in null to ref an empty objectconst searchInput = useRef(null);function handleClearSearch() {// current references the text input once App mountssearchInput.current.value = "";// useRef can store basically any value in its .current propertysearchInput.current.focus();}return (<form><inputtype="text"onChange={event => setQuery(event.target.value)}ref={searchInput}/><button type="submit">Search</button><button type="button" onClick={handleClearSearch}>Clear</button></form>);
}
高級掛鉤 (Advanced Hooks)
上下文和useContext (Context and useContext)
In React, we want to avoid the following problem of creating multiple props to pass data down two or more levels from a parent component:
在React中,我們希望避免以下問題:創建多個道具以將數據從父組件向下傳遞到兩個或多個級別:
// Context helps us avoid creating multiple duplicate props
// This pattern is also called props drilling:
function App() {// we want to pass user data down to Headerconst [user] = React.useState({ name: "Fred" });return ({/* first 'user' prop */}<Main user={user} />);
}const Main = ({ user }) => (<>{/* second 'user' prop */}<Header user={user} /><div>Main app content...</div></>
);const Header = ({ user }) => <header>Welcome, {user.name}!</header>;
Context is helpful for passing props down multiple levels of child components from a parent component.
上下文有助于將道具從父組件向下傳遞到多個子組件級別。
// Here is the previous example rewritten with Context
// First we create context, where we can pass in default values
const UserContext = React.createContext();
// we call this 'UserContext' because that's what data we're passing downfunction App() {// we want to pass user data down to Headerconst [user] = React.useState({ name: "Fred" });return ({/* we wrap the parent component with the provider property */}{/* we pass data down the computer tree w/ value prop */}<UserContext.Provider value={user}><Main /></UserContext.Provider>);
}const Main = () => (<><Header /><div>Main app content...</div></>
);// we can remove the two 'user' props, we can just use consumer
// to consume the data where we need it
const Header = () => ({/* we use this pattern called render props to get access to the data*/}<UserContext.Consumer>{user => <header>Welcome, {user.name}!</header>}</UserContext.Consumer>
);
The useContext hook can remove this unusual-looking render props pattern, however, to be able to consume context in whatever function component we like:
useContext鉤子可以刪除這種看起來異常的渲染道具模式,以便能夠在我們喜歡的任何函數組件中使用上下文:
const Header = () => {// we pass in the entire context object to consume itconst user = React.useContext(UserContext);// and we can remove the Consumer tagsreturn <header>Welcome, {user.name}!</header>;
};
減速器及使用 (Reducers and useReducer)
Reducers are simple, predictable (pure) functions that take a previous state object and an action object and return a new state object. For example:
約簡器是簡單,可預測(純)的函數,它們采用先前的狀態對象和操作對象并返回新的狀態對象。 例如:
// let's say this reducer manages user state in our app:
function reducer(state, action) {// reducers often use a switch statement to update state// in one way or another based on the action's type propertyswitch (action.type) {// if action.type has the string 'LOGIN' on itcase "LOGIN":// we get data from the payload object on actionreturn { username: action.payload.username, isAuth: true };case "SIGNOUT":return { username: "", isAuth: false };default:// if no case matches, return previous statereturn state;}
}
Reducers are a powerful pattern for managing state that is used in the popular state management library Redux (common used with React).
Reducer是一種流行的狀態管理庫Redux(與React共同使用)中用于管理狀態的強大模式。
Reducers can be used in React with the useReducer hook in order to manage state across our app, as compared to useState (which is for local component state).
與useState(用于本地組件狀態)相比,Reducer可與useReducer掛鉤一起在React中使用,以管理整個應用程序中的狀態。
useReducer can be paired with useContext to manage data and pass it around components easily.
可以將useReducer與useContext配對使用,以管理數據并輕松地將其傳遞給組件。
Thus useReducer + useContext can be an entire state management system for our apps.
因此useReducer + useContext可以成為我們應用程序的整個狀態管理系統。
const initialState = { username: "", isAuth: false };function reducer(state, action) {switch (action.type) {case "LOGIN":return { username: action.payload.username, isAuth: true };case "SIGNOUT":// could also spread in initialState herereturn { username: "", isAuth: false };default:return state;}
}function App() {// useReducer requires a reducer function to use and an initialStateconst [state, dispatch] = useReducer(reducer, initialState);// we get the current result of the reducer on 'state'// we use dispatch to 'dispatch' actions, to run our reducer// with the data it needs (the action object)function handleLogin() {dispatch({ type: "LOGIN", payload: { username: "Ted" } });}function handleSignout() {dispatch({ type: "SIGNOUT" });}return (<>Current user: {state.username}, isAuthenticated: {state.isAuth}<button onClick={handleLogin}>Login</button><button onClick={handleSignout}>Signout</button></>);
}
編寫自定義鉤子 (Writing custom hooks)
Hooks were created to easily reuse behavior between components.
創建掛鉤是為了輕松重用組件之間的行為。
They're a more understandable pattern than previous ones for class components, such as higher-order components or render props
對于類組件(例如高階組件或渲染道具),它們是比以前的模式更易于理解的模式
What's great is that we can create our own hooks according to our own projects' needs, aside from the ones we've covered that React provides:
很棒的是,除了我們已經介紹的React提供的那些功能之外,我們還可以根據自己項目的需要創建自己的鉤子:
// here's a custom hook that is used to fetch data from an API
function useAPI(endpoint) {const [value, setValue] = React.useState([]);React.useEffect(() => {getData();}, []);async function getData() {const response = await fetch(endpoint);const data = await response.json();setValue(data);};return value;
};// this is a working example! try it yourself (i.e. in codesandbox.io)
function App() {const todos = useAPI("https://todos-dsequjaojf.now.sh/todos");return (<ul>{todos.map(todo => <li key={todo.id}>{todo.text}</li>}</ul>);
}
鉤子規則 (Rules of hooks)
There are two core rules of using React hooks that we cannot violate for them to work properly:
使用React掛鉤有兩個我們不能違反的核心規則,它們才能正常工作:
- Hooks can only be called at the top of components (they cannot be in conditionals, loops or nested functions) 掛鉤只能在組件的頂部調用(它們不能在條件,循環或嵌套函數中)
- Hooks can only be used within function components (they cannot be in normal JavaScript functions or class components) 掛鉤只能在函數組件內使用(不能在常規JavaScript函數或類組件中使用)
function checkAuth() {// Rule 2 Violated! Hooks cannot be used in normal functions, only componentsReact.useEffect(() => {getUser();}, []);
}function App() {// this is the only validly executed hook in this componentconst [user, setUser] = React.useState(null);// Rule 1 violated! Hooks cannot be used within conditionals (or loops)if (!user) {React.useEffect(() => {setUser({ isAuth: false });// if you want to conditionally execute an effect, use the// dependencies array for useEffect}, []);}checkAuth();// Rule 1 violated! Hooks cannot be used in nested functionsreturn <div onClick={() => React.useMemo(() => doStuff(), [])}>Our app</div>;
}
下一步是什么 (What's Next)
There are many other React concepts to learn, but these are the ones I believe you must know before any others to set you on the path to React mastery in 2020.
還有許多其他的React概念需要學習,但我相信您必須先了解這些概念,才能使您踏上2020年的React掌握道路。
Want a quick reference of all of these concepts?
是否需要所有這些概念的快速參考?
Download a complete PDF cheatsheet of all this info right here.
在此處下載所有這些信息的完整PDF速查表。
Keep coding and I'll catch you in the next article!
繼續編碼,我將在下一篇文章中幫助您!
想要成為JS大師嗎? 加入2020年JS訓練營 (Want To Become a JS Master? Join the 2020 JS Bootcamp )

Follow + Say Hi! 👋 Twitter ? codeartistry.io
關注+說聲嗨! 👋 Twitter的 ? codeartistry.io
翻譯自: https://www.freecodecamp.org/news/the-react-cheatsheet-for-2020/
react 示例