likes
comments
collection
share

前端速看:React18更新一览清单

作者站长头像
站长
· 阅读数 33
截至到现在,React18已经出来半个月了,是否还有小伙伴不太了解呢? 我给大家整理一份更新清单,包含了较常用的更新,列举了一些不错的案例和链接,方便大家快速上手和深入了解!

浏览器最低兼容提升

由于新版react使用了Promise,Symbol,Object.assign,所以要像IE和其他过于低版本的浏览器需要借助polyfill了

新的根API

// 之前根API,使用ReactDOM.render
ReactDOM.render(<App/>, document.getElementById('root'))

// 现在为了更符合工程学,和vue3一样,都引入了新的根api
import { createRoot } from 'react-dom/client';
const el = document.getElementById('app');
const root = createRoot(el);
root.render(<App />);

异步任务也将"批处理"

// 之前在异步任务里react无法拦截hooks进行批处理
setTimeout(()=>{ // 这样会更新两次视图
    setCount(val => val+1)
    setNum(val => val+1)
})
// 但是在18里将只会更新一次

转换更新API

// 当我们从一个视图转到另个视图时,一般都是非紧急更新,不像点击事件这种需要视图立即进行反馈
// 过渡更新不会阻塞与其他视图的交互

// 函数组件
import {useTransition} from 'react';

function App() {
  // isPending 表示是否在过渡状态中
  const [isPending, startTransition] = useTransition();
  const [count, setCount] = useState(0);
  
  function handleClick() {
    startTransition(() => {
      setCount(c => c + 1);
    })
  }

  return (
    <div>
      {isPending && <Spinner />}
      <button onClick={handleClick}>{count}</button>
    </div>
  );
}

// 类组件 不提供isPending这种状态值
import {Component, startTransition} from 'react';

class App extends Component{
    // ...
    // 紧急事件
    setInputValue(input);
    
    startTransition(() => {
      // 过渡事件
      setSearchQuery(input);
    });
    // ...
}

延迟hook: useDeferredValue

// 此hook有点类似于防抖,但是它没有固定的时间延迟,它会在React完成其他工作后立即进行更新,并且是可中断的,不会阻碍用户与其他视图的交互

const [deferredValue] = useDeferredValue(value);

Suspence

如果组件树的一部分尚未准备好显示,Suspense 允许您以声明方式指定组件树的加载状态:

// 我们来看这样一个例子,在过渡期间会变透明
const [isPending, startTransition] = useTransition();

function handleClick() {
  startTransition(() => {
    setTab('comments');
  });
}

<Suspense fallback={<Spinner />}>
  <div style={{ opacity: isPending ? 0.8 : 1 }}>
    {tab === 'photos' ? <Photos /> : <Comments />}
  </div>
</Suspense>

// useDeferredValue 结合 Suspense, 防止子组件在紧急更新时重新渲染
function Typeahead() {
  const query = useSearchQuery('');
  const deferredQuery = useDeferredValue(query);

  const suggestions = useMemo(() =>
    <SearchSuggestions query={deferredQuery} />,
    [deferredQuery]
  );

  return (
    <>
      <SearchInput query={query} />
      <Suspense fallback="Loading results...">
        {suggestions}
      </Suspense>
    </>
  );
}

还有更多实用的例子详看:suspense官方详解

useId

// 生成稳定的唯一ID
  function Checkbox() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Do you like React?</label>
      <input id={id} type="checkbox" name="react"/>
    </>
  );
};

// 多个ID时
function NameFields() {
  const id = useId();
  return (
    <div>
      <label htmlFor={id + '-firstName'}>First Name</label>
      <div>
        <input id={id + '-firstName'} type="text" />
      </div>
      <label htmlFor={id + '-lastName'}>Last Name</label>
      <div>
        <input id={id + '-lastName'} type="text" />
      </div>
    </div>
  );
}

TypeScript注解修复

children现在需要明确定义出来,具体原因可看我之前的文章 React+TypeScript必备

interface MyButtonProps {
  color: string;
  children?: React.ReactNode;
}
以上列举了较常用的更新,要想看更详细的更新细节可以进入 React18.0.0新功能介绍