截至到当初,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新性能介绍
发表回复