您的位置:首页 > Web前端 > React

微信授权扫码点餐-新特性React16

2021-05-17 23:58 971 查看
首先,需要对静态方法做一个理解。static静态方法,在es5中怎么实现呢?网易云课堂微信授权扫码点餐-新特性React16
function Person() {}
Person.getCount = function () {}
以上就是static静态方法的原理。由于“this”只能获取属性是根据原型链,而静态方法不在原型链上,所以,在组件实例内无通过this调用static方法,static方法也无法根据"this"调用实例的其他方法。
就防止在getDerivedStateFromProps 对组件实例的错误操作。
再次,getDerivedStateFromProps用来做什么用呢?
当组件实例化、接收到新的props时,会调用该方法。方法返回一个对象,这个对象会被更新到组件的state上。如果返回空,那么不对state做更新。
// 以下代码实现,更新name属性到state上;static getDerivedStateFromProps (nextProps, prevState) {
    return {
        name: nextProps.name
    };}// 上面的代码在以前版本中// 你可能会用以下这样做,虽然这样做看起来也没问题,用上面的方法更加安全,不会对this做误操作componentWillReceiveProps (nextProps) {
    if (this.state.name !== nextProps.name) {
        this.setState({
            name: nextProps.name
        });
    }}


b.如何理解getSnapshotBeforeUpdate(prevProps, prevState)?

首先,从字面来理解“snapshot”是快照的意思。在dom更前之前调用。返回的值将被传给componentDidUpdate(prevProps, prevState, snaphot)。
这个会比较少用到,但对于处理比如数据更新后的滚动条的差异滚动,对用户体验,很有帮助。


c.如何理解componentDidCatch(error, info)?

以往,当组件发生错误(可以用throw new Error模拟)时,会导致整个react程序死掉,这对于程序的稳定性来说非常不好。
componentDidCatch可以捕获子组件中任何一个错误,捕获到错误后可以对错误进行处理。
如果发生错误的组件的父组件没有设置componentDidCatch错误捕获,将继续递归父组件的父组件中的componentDidCatch,找到则停止。
// 简单的错误捕获componentDidCatch (error, info) {
    this.setState({
        error: true
    });}render () {
    if (this.state.error) {
        return <div>子组件发生异常了</div>
    }
    
    // 其他代码}

第二:优化了哪些语法

1: ref优化

ref有很多作用,通过ref父组件可以调用子组件内的方法,配合ReactDOM.findDOMNode(ref) 可以获取到组件对应的dom。ref与key一样无法通过this.props.ref获取;

以前版本的react,给子组件添加ref=“inputName”,就可以通过this.refs['inputName']获取子组件实例。然后可以进行一些操作。


React16中有两种创建Ref的方法:

constructor () {
    this.inputNameRef = React.createRef();
    this.switchRef = React.createRef();}render () {
    // 通过this.inputNameRef.current 可以获取到input实例    return (
        <div>
             <input ref={this.inputNameRef} />
             <Switch ref={this.switchRef} />
        </div>
    )}


render () {
    // 通过回调ref的方式实现    // 通过this.inputNameRef 可以获取到input实例    // this.switchRef可以获取Switch的实例    return (
        <div>
             <input ref={(ref) => this.inputNameRef = ref} />
             <Switch ref={(ref) => this.switchRef = ref} />
        </div>
    )}

那,既然ref和key可以一样不能用this.props获取,有没有办法传给子组件呢?这样就可以实现在组件中调用子子组件(比如子组件中的input)了。

答案是肯定的。

也有两种方法:

render () {
    // 假设this.switchRef已经在constructor里创建了,那么可以通过其他属性传递。    // 在子组件中可以通过this.props.forRef。    // 注:forRef 为随便名只要不是react内置的名称就行    return (
        <Switch forRef={this.switchRef} />
    );}


// 通过React.forwardRef 传递export default React.forwardRef((props, ref) => {
    return (
        <div>
            <OtherChild />
            <Switch ref={ref} />
            <OtherChild2 />
        </div>
    )});


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: