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;
所以使用它,或者简单地使用 this.props.history
关于javascript - 在带有 React 的 ES6 中,我可以只解构一个对象一次以便在多个方法中使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42344026/