important sandbox

important chapter

DEEP DIVE

未完成文档

Syntax Export statement Import statement
Default export default function Button() {} import Button from ‘./button.js’;
Named export function Button() {} import { Button } from ‘./button.js’;

image.png

image.png
image.png
实际上👇两个是等价的
image.png

image.png

  • In JSX, {cond && } means “if cond, render , otherwise nothing”.

Array.prototype.shift()
shift 方法移除索引为 0 的元素(即第一个元素),并返回被移除的元素,其他元素的索引值随之减 1。如果 length 属性的值为 0 (长度为 0),则返回 undefined。

React offers a “Strict Mode” in which it calls each component’s function twice during development. By calling the component functions twice, Strict Mode helps find components that break these rules.

但在 React 中,你可以在渲染时读取三种输入:props、state和context。 应始终将这些输入视为只读。

Hooks are special functions that let your components use React features

嵌套的标签都有点击事件的时候,比如点击div>的button,会先响应内层的再冒泡到外层的
All events propagate in React except onScroll, which only works on the JSX tag you attach it to

If you want to prevent an event from reaching parent components, you need to call e.stopPropagation()

  1. function Button({ onClick, children }) {
  2. return (
  3. <button onClick={e => {
  4. e.stopPropagation();
  5. onClick();
  6. }}>
  7. {children}
  8. </button>
  9. );
  10. }

image.png

Some browser events have default behavior associated with them. For example, a

submit event, which happens when a button inside of it is clicked, will reload the whole page by default

Some browser events have default behavior associated with them. For example, a submit event, which happens when a button inside of it is clicked, will reload the whole page by default

export default function Signup() {
  return (
    <form onSubmit={e => {
      e.preventDefault();//👈
      alert('Submitting!');
    }}>
      <input />
      <button>Send</button>
    </form>
  );
}

useState()
https://codesandbox.io/s/ts17o?file=/App.js&from-sandpack=true

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);//这里是数组的解构赋值

  function handleClick() {
    setIndex(index + 1);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
      <p>
        {sculpture.description}
      </p>
    </>
  );
}

In React, useState, as well as any other function starting with “use,” is called a Hook.
Hooks are special functions that are only available while React is rendering (which we”ll get into in more detail on the next page). They let you “hook into” different React features.

当两个state关联程度很高的时候,应该把他们放在一起

Setting state only changes it for the next render.
https://codesandbox.io/s/vgete?file=/App.js&from-sandpack=true

setPerson({
      ...person,
      lastName: e.target.value
    });

☐You can also use the [ and ] braces inside your object definition to specify a property with dynamic name.
https://codesandbox.io/s/rpcdf?file=/App.js&from-sandpack=true

setPerson({
  ...person, // Copy other fields
  artwork: { // but replace the artwork
    ...person.artwork, // with the same one
    city: 'New Delhi' // but in New Delhi!
  }
});

👆Immer is a great way to keep the update handlers concise, especially if there’s nesting in your state, and copying objects leads to repetitive code

updatePerson(draft => {
  draft.artwork.city = 'Lagos';
});

https://github.com/immerjs/use-immer

avoid (mutates the array) prefer (returns a new array)
adding push, unshift concat, […arr] spread syntax (example)
removing pop, shift, splice filter, slice (example)
replacing splice, arr[i] = … assignment map (example)
sorting reverse, sort copy the array first (example)

find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。

  1. Identify your component’s different visual states
  2. Determine what triggers those state changes
  3. Represent the state in memory using useState
  4. Remove any non-essential state variables⭐(state越少越好)
  5. Connect the event handlers to set the state

image.png

example:

const [isEmpty, setIsEmpty] = useState(true);
const [isTyping, setIsTyping] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [isError, setIsError] = useState(false);

⬇️去掉不需要的state

const [answer, setAnswer] = useState('');
const [error, setError] = useState(null);
const [status, setStatus] = useState('typing'); // 'typing', 'submitting', or 'success'

Principles for structuring state

  • Group related state. If you always update two or more state variables at the same time, consider merging them into a single state variable.
  • Avoid contradictions in state. When the state is structured in a way that several pieces of state may contradict and “disagree” with each other, you leave room for mistakes. Try to avoid this.
  • Avoid redundant state. If you can calculate some information from the component’s props or its existing state variables during rendering, you should not put that information into that component’s state.
  • Avoid duplication in state. When the same data is duplicated between multiple state variables, or within nested objects, it is difficult to keep them in sync. Reduce duplication when you can.
  • Avoid deeply nested state. Deeply hierarchical state is not very convenient to update. When possible, prefer to structure state in a flat way.

image.png
so,在这个例子中,两次render的会被认为是同一个,从而不reset state
而在这个例子中,两个被不同的tag包裹, 被认为是不同的, 所以就reset state了
用不同的key也可以让其被视为不同的组件

{isPlayerA ? (
  <Counter key="Taylor" person="Taylor" />
) : (
  <Counter key="Sarah" person="Sarah" />
)}
//Remember that keys are not globally unique. They only specify the position within the parent.

image.png

In a real chat app, you’d probably want to recover the input state when the user selects the previous recipient again. There are a few ways to keep the state “alive” for a component that’s no longer visible:

  • You could render all chats instead of just the current one, but hide all the others with CSS. The chats would not get removed from the tree, so their local state would be preserved. This solution works great for simple UIs. But it can get very slow if the hidden trees are large and contain a lot of DOM nodes.
  • You could lift the state up and hold the pending message for each recipient in the parent component. This way, when the child components get removed, it doesn’t matter, because it’s the parent that keeps the important information. This is the most common solution.
  • You might also use a different source in addition to React state. For example, you probably want a message draft to persist even if the user accidentally closes the page. To implement this, you could have the Chat component initialize its state by reading from the localStorage, and save the drafts there too.

No matter which strategy you pick, a chat with Alice is conceptually distinct from a chat with Bob, so it makes sense to give a key to the tree based on the current recipient.

image.png
添加{null}后两次render的form会被视为同一个,保留state👉https://codesandbox.io/s/6hyb0?file=/App.js&from-sandpack=true
但是可以会造成问题:有人认为这个Null没用就把他移走了

Reducer

reducer vs useState 👉 功能更复杂的时候尝试用reducer

  • Code size: Generally, with useState you have to write less code upfront. With useReducer, you have to write both a reducer function and dispatch actions. However, useReducer can help cut down on the code if many event handlers modify state in a similar way.
  • Readability: useState is very easy to read when the state updates are simple. When they get more complex, they can bloat your component’s code and make it difficult to scan. In this case, useReducer lets you cleanly separate the how of update logic from the what happened of event handlers.
  • Debugging: When you have a bug with useState, it can be difficult to tell where the state was set incorrectly, and why. With useReducer, you can add a console log into your reducer to see every state update, and why it happened (due to which action). If each action is correct, you’ll know that the mistake is in the reducer logic itself. However, you have to step through more code than with useState.
  • Testing: A reducer is a pure function that doesn’t depend on your component. This means that you can export and test it separately in isolation. While generally it’s best to test components in a more realistic environment, for complex state update logic it can be useful to assert that your reducer returns a particular state for a particular initial state and action.
  • Personal preference: Some people like reducers, others don’t. That’s okay. It’s a matter of preference. You can always convert between useState and useReducer back and forth: they are equivalent!

image.png

react的props.children 代表标签之间的内容

context

https://beta.reactjs.org/learn/passing-data-deeply-with-context
跨多辈传递值或多个不同组件共享一个值的时候使用userContext

clearInterval
Ref.current

refs state
useRef(initialValue) returns { current: initialValue } useState(initialValue) returns the current value of a state variable and a state setter function ( [value, setValue])
Doesn’t trigger re-render when you change it. Triggers re-render when you change it.
Mutable—you can modify and update current’s value outside of the rendering process. “Immutable”—you must use the state setting function to modify state variables to queue a re-render.
You shouldn’t read (or write) the current value during rendering. You can read state at any time. However, each render has its own snapshot of state which does not change.

If your component needs to store some value, but it doesn’t impact the rendering logic, choose refs.

the most common use case for a ref is to access a DOM element

Hooks must only be called at the top-level of your component. You can’t call useRef in a loop, in a condition, or inside a map() call.

Refs are an escape hatch. You should only use them when you have to “step outside React.” Common examples of this include managing focus, scroll position, or calling browser APIs that React does not expose

  • Refs are a generic concept, but most often you’ll use them to hold DOM elements.
  • You instruct React to put a DOM node into myRef.current by passing
    .
  • Usually, you will use refs for non-destructive actions like focusing, scrolling, or measuring DOM elements.
  • A component doesn’t expose its DOM nodes by default. You can opt into exposing a DOM node by using forwardRef and passing the second ref argument down to a specific node.
  • Avoid changing DOM nodes managed by React.
  • If you do modify DOM nodes managed by React, modify parts that React has no reason to update.

Escape Hatches👈为什么要叫逃生舱? 意为逃离react的接管,完全由自己掌控
逃离之后用什么操作DOM?于是引出了refs

Hooks

side effect

  • pure
    • Components should only return their JSX, and not change any objects or variables that existed before rendering
    • same input, same output
    • 可以检测是否pure
    • pure的好处:
      • 让组件在不同的环境下运行:在服务器上运行的时候,能处理并发
      • 通过skip渲染来提升性能
      • 渲染中出现更改,react可以随时终止并重新渲染而不出错
  • side effect
    • While functional programming relies heavily on purity, at some point, somewhere, something has to change. That’s kind of the point of programming! These changes—updating the screen, starting an animation, changing the data—are called side effects. They’re things that happen “on the side,” not during rendering.

useEffect

由两个参数
useEffect(函数,数组)
第一个参数填写回调函数,第二个参数是一个数组,数组内接受回调函数内使用到的状态参数,一旦在组件内改变了状态参数,则会触发副作用useEffect的回调函数执行
比如:

  useEffect(() => {
    (async () => {
      const data = await getList(query)
      console.log('data', data)
      setData(data)
    })()
  }, [query])

第二个参数不填可能会反复执行,填空数组可能会至执行一次,详见👉https://juejin.cn/book/6966551262766563328/section/6967228489208430603

自定义Hook⭐

可以用于抽离出一些可以复用的逻辑,比如提取一个useApi.js 详细内容参考👉https://juejin.cn/book/6966551262766563328/section/6967228489208430603

import React, { useEffect, useState } from 'react'
// 模拟请求
const getList = (query) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('query', query)
      resolve([6, 7, 8, 9, 10])
    }, 3000)
  })
}
// 自定义 hook
const useApi = () => {
  const [data, setData] = useState([1, 2, 3, 4, 5])
  const [query, setQuery] = useState('')

  useEffect(() => {
    (async () => {
      const data = await getList()
      console.log('data', data)
      setData(data)
    })()
  }, [query])

  return [{ data }, setQuery];
}

export default useApi

useMemo

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
//返回一个memorized值

第一个为参数为函数,第二个是依赖项,通常是需要监听的内容

把“创建”函数和依赖项数组作为参数传入 useMemo,它仅会在某个依赖项改变时才重新计算 memoized 值。这种优化有助于避免在每次渲染时都进行高开销的计算。

记住,传入 useMemo 的函数会在渲染期间执行。请不要在这个函数内部执行与渲染无关的操作,诸如副作用这类的操作属于 useEffect 的适用范畴,而不是 useMemo。

如果没有提供依赖项数组,useMemo 在每次渲染时都会计算新的值。

你可以把 useMemo 作为性能优化的手段,但不要把它当成语义上的保证。将来,React 可能会选择“遗忘”以前的一些 memoized 值,并在下次渲染时重新计算它们,比如为离屏组件释放内存。先编写在没有 useMemo 的情况下也可以执行的代码 —— 之后再在你的代码中添加 useMemo,以达到优化性能的目的。
example:https://juejin.cn/book/6966551262766563328/section/6967228489208430603

useCallback

和useMemo类似,useCallback(fn, deps) 相当于 useMemo(() => fn, deps)