Error Boundary 处理错误
Error Boundary
指能够捕获其所有子组件的错误并对错误做优雅处理的组件,这种优雅错误处理包括上报错误日志、展示出错提示而不是卸载整个组件树。使用componentDidCatch
生命周期方法来处理捕获到的错误。import React, { Component } from 'react'; const Profile = ({ user }) => (<div>name: {user.name}</div>); // 封装为错误处理组件 class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; } // componentDidCatch react16加入的钩子函数 componentDidCatch(err, info) { console.log(err, info); this.setState({ hasError: true }); // sendErrorReport(err, info); 此处为项目中一般会将错误上传至服务器 } render() { if (this.state.hasError) { return <div>Oops, something went wrong!</div>; } return this.props.children; } } class App extends Component { constructor(props) { super(props); this.state = { user: { name: 'wangshijun' }, }; } onClick() { this.setState({ user: null }); } render() { return ( <div> {/* ErrorBoundary一般用在特定的地方,监视错误信息 */} <ErrorBoundary> <Profile user={this.state.user} /> </ErrorBoundary> <button onClick={this.onClick.bind(this)}>Update</button> </div> ); } } export default App;
在 render 中返回没有容器元素的多个元素
import React, { Component } from 'react'; const Fruits = () => [ <li key="1">Pear</li>, <li key="2">Weater Melon</li>, ]; class App extends Component { render() { return [ <ul> <li>Apple</li> <li>Banana</li> <Fruits /> </ul>, <div>this is a div</div>, ]; } } export default App;
Text Only Component
import React, { Component } from 'react'; const Comment = ({ text }) => text.replace(':)', '[smile]'); class App extends Component { render() { return ( <div> <Comment text="Text only components are awesome :)" /> </div> ); } } export default App;
用 createPortal 把组件渲染到当前组件树之外,弹框(遮罩)
默认情况下,React组件树 是和 DOM树 完全对应的,但是这样会给部分 UI 组件带来限制,比如常见的蒙层、进度条,React 16 提供的 portal 特性能把组件树的部分渲染到当前组件树之外。
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class Overlay extends Component { constructor(props) { super(props); this.container = document.createElement('div'); document.body.appendChild(this.container); } // 记得要卸载前remove componentWillUnmount() { document.body.removeChild(this.container); } render() { // createPortal(content, Element) return ReactDOM.createPortal( <div className="overlay"> <span className="overlay__close" onClick={this.props.onClose}> × </span> {this.props.children} </div>, this.container ); } } class App extends Component { constructor(props) { super(props); this.state = { overlayActive: true }; } closeOverlay() { this.setState({ overlayActive: false }); } render() { return ( <div> <h2>Dashboard</h2> {this.state.overlayActive && <Overlay onClose={this.closeOverlay.bind(this)}>overlay content</Overlay>} </div> ); } } export default App;
在 setState 时用 null 避免不必要的渲染
setState
接收一个参数为state的函数,通过将返回值设置为null
来避免不必要的渲染。selectCity(e) { const newValue = e.target.value; this.setState((state) => { if (state.city === newValue) { return null; } return { city: newValue }; }); }
react 16
最新推荐文章于 2024-07-22 00:47:37 发布