javascript - 在带有 React 的 ES6 中,我可以只解构一个对象一次以便在多个方法中使用吗?

标签 javascript reactjs ecmascript-6 redux es6-class

import React, { Component } from 'react'
import { connect } from 'react-redux';

export default function(strategies = []) {
    class Authentication extends Component {
        constructor() {
            super()
            this.state = {
                allGreen: true
            }
        }
        componentWillMount() {
            const { history } = this.props
            strategies.map(strategy => {
                if (!this.props.auth[strategy]) {
                    this.setState({ allGreen: false })
                    history.replace('/')
                }
            })
        }
        componentWillUpdate(nextProps, nextState) {
            const { history } = this.props
            strategies.map(strategy => {
                if (!nextProps.auth[strategy]) {
                    this.setState({ allGreen: false })
                    history.replace('/')
                }
            })
        }
        render() {
            if (!this.state.allGreen) return (<div></div>)

            return this.props.children
        }
    }

    function mapStateToProps(state) {
        return {
            auth: state.auth
        }
    }

    return connect(mapStateToProps)(Authentication)
}

我通常在 ES6 中使用“析构函数对象”

例如 const { History } = this.props 之类的。

但是,我想知道是否有一种有效的方法可以仅销毁一个对象,并在所有组件的方法中使用它。(componentWillMount,componentWillUpdate ...)

上图中,我在 componentWillMount 方法和 componentWillUpdate 方法中两次使用了对象销毁。 ( const { 历史 } = this.props )

我只想破坏对象一次!有什么解决办法吗?

最佳答案

多次使用解构不会出现性能问题(如果您担心的话,您就不会扩展整个对象)。

ES 6 代码如下::

const aaa = {
  a: 5,
  b: 'ffff'
}

const { bbb } = aaa;

...被翻译为...

var aaa = {
  a: 5,
  b: 'ffff'
};

var bbb = aaa.bbb;

尝试https://babeljs.io

所以使用它,或者简单地使用 this.props.history

关于javascript - 在带有 React 的 ES6 中,我可以只解构一个对象一次以便在多个方法中使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42344026/

相关文章:

javascript - Angular UI Bootstrap 模态 - 使用自定义模态窗口

javascript - 如何通过JS绘制的表格上的按钮删除行

javascript - XHR 请求 -> 获取 ERR_EMPTY_RESPONSE

reactjs - React-router如何重定向到服务器端口

javascript - JS 代理 HTML5 Canvas 上下文

javascript - 通过 UserManager 使用服务时,User 为 Null

javascript - a.toString().replace(/^(\d)$/, "0$1")?

javascript - React 在更新实时数据库时运行无限循环

reactjs - 为什么 React Router location props 只能在 Context 中使用?

arrays - ES6 : Merge two arrays into an array of objects