前言
這里將列出react16所有新特性。我覺(jué)得重要的:
1馆截、render 支持返回?cái)?shù)組和字符串
2、新生命周期getDerivedStateFromProps,getSnapshotBeforeUpate
3框产、createPortal,modal傳送到任意位置
4错洁、新增指針事件
5秉宿、給函數(shù)式組件加memo,實(shí)現(xiàn)性能優(yōu)化
6屯碴、懶加載組件描睦,lazy, suspense
7、react hooks
1导而、render 支持返回?cái)?shù)組和字符串
class Example extends React.Component {
render() {
return [
<div key="1">first element</div>,
<div key="2">second element</div>,
];
}
}
2忱叭、Error Boundary(錯(cuò)誤邊界)
<ErrorBoundary>
<BuggyCounter />
</ErrorBoundary>
包裹在組件外,組件出錯(cuò)嗡载,可以拋出異常窑多,但是不會(huì)讓頁(yè)面白屏。
3洼滚、createPortal
ReactDOM.createPortal(
// Any valid React child: JSX, strings, arrays, etc.
this.props.children,
// A DOM element
this.el,
)
傳送門(mén)埂息,通過(guò)createPortal生成的組件,可以任意定義你需要放的位置遥巴。比如彈框放在body上面千康,就可以document.body..appendChild(this.el)。
4铲掐、自定義屬性
ReactDOM.render(
<h1 custom="hello">Hello, world!</h1>,
document.getElementById("root")
);
custom就是自定義的屬性拾弃,以前的有白名單的,自定義就拋錯(cuò)摆霉。
5豪椿、優(yōu)化SSR
- 生成更簡(jiǎn)潔的HTML
- 寬松的客戶端一致性校驗(yàn)
- 無(wú)需提前編譯
- react 16服務(wù)端渲染速度更快
- 支持流式渲染
6奔坟、Fiber:react對(duì)于對(duì)比更新的一種新算法,它影響著生命周期函數(shù)的變化跟異步渲染搭盾。學(xué)習(xí)地址
7咳秉、 Fragement:可以通過(guò)Fragement直接返回多個(gè)組件,好處是有時(shí)間我們不想用div鸯隅,但是不得不用導(dǎo)致嵌套過(guò)深。
render() {
return (
<>
<ChildA />
<ChildB />
</>
);
}
或者
render() {
return (
<Fragement>
1
<h2>2</h2>
</Fragement>
);
}
8炕舵、新的生命周期(新算法導(dǎo)致生命周期更改)
拋棄并兼容:componentWillMount, componentWillReceiveProps,componentWillUpdate
1徊件、getDerivedStateFromProps替換componentWillReceiveProps
2、getSnapshotBeforeUpate替代componentWillUpdate
9、新的context API:全局變量捎迫,不需要向之前一樣傳遞下去
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
class Toolbar extends React.Component {
static contextType = ThemeContext;
render() {
return <Button theme={this.context} />;
}
}
10崔兴、createRef API:refs擴(kuò)展
react16之前:
<input type="text" ref={element => this.textInput = element} />
react16:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
render() {
return <input type="text" ref={this.inputRef} />;
}
componentDidMount() {
this.inputRef.current.focus();
}
}
11堰燎、forwardRef API: 父組件需要將自己的引用傳給子組件赊淑,自行研究吧,個(gè)人不喜歡用处渣。
12、strictMode component:嚴(yán)格模式用來(lái)幫助開(kāi)發(fā)者發(fā)現(xiàn)潛在問(wèn)題的工具
- 識(shí)別出使用不安全生命周期的組件
- 對(duì)使用string ref進(jìn)行告警
- 對(duì)使用findDOMNode進(jìn)行告警
- 探測(cè)某些產(chǎn)生副作用的方法
- 對(duì)使用棄用context API進(jìn)行警告
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Footer />
</div>
);
}
13柑贞、新增指針事件(鼠標(biāo)有决,觸控筆书幕,或者手指觸摸)
- onPointerDown
- onPointerMove
- onPointerEnter
- onPointerLeave
- onPointerOver
- onPointerOut
14新荤、React Profiler:谷歌插件下載即可,可以檢測(cè)到組件渲染耗時(shí)台汇。
15苛骨、memo
import React, { memo } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function Demo(props) {
console.log("render");
return <div>{props.name}</div>;
}
const Demo1 = memo(function Demo(props) {
console.log("render");
return <div>{props.name}</div>;
});
class App extends React.Component {
state = { count: 0 };
handleClick = () => {
this.setState({ count: 1 });
};
render() {
return (
<div className="App">
<h1>Hello Memo</h1>
<button onClick={this.handleClick}>
This is Memo Demo{this.state.count}
</button>
<Demo1 name={"daisy"} />
</div>
);
}
}
在你的函數(shù)前面加Memo就可以像PureComponent實(shí)現(xiàn)shouldComponentUpdate優(yōu)化渲染功能。
16苟呐、lazy智袭、suspense
<!--import B from "./B";-->
// 需要用到的時(shí)候才加載進(jìn)來(lái),當(dāng)然還有預(yù)加載更好
const B = lazy(() => import("./B"));
<Suspense fallback={<div>Loading...</div>}>
<TabPanel>
<B />
</TabPanel>
</Suspense>
17掠抬、簡(jiǎn)化static contextType吼野,就是不需要包裹c(diǎn)onsumer,用this.context即可两波。這個(gè)文檔需要各位親好好查查瞳步,就是新版context的使用方式闷哆,redux的connect原理就是基于它而生。
18单起、static getDerivedStateFromError
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
// 更新state所以下次render可以立刻顯示fallback UI
return { hasError: true };
}
componentDidCatch(error, info) {
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
最牛逼的登場(chǎng)了1д!嘀倒!
19屈留、react hooks:建議好好研究下,我這邊只說(shuō)個(gè)大概测蘑。
之前class
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
hooks
import React, { useState } from 'react';
function Example() {
// count表示預(yù)設(shè)置參數(shù)灌危;setCount表示方法,useState(0)設(shè)置初始值0
const [count, setCount] = useState(0);
const [ok, setOk] = useState("yes");
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}