我正在学习javascript,并且在尝试在解构时为变量赋予默认值时,我有点坚持使用ES6语法.基本上,我试图分配一个给出对象属性值的变量,如果值为false/null/undefined,我希望它是一个空对象.例如,
let foo = {
prop1: 'hello!',
prop2: null
}
const prop1 = foo.prop1 || {}
const prop2 = foo.prop2 || {}
console.log(prop1) // hello!
console.log(prop2) // {}
Run Code Online (Sandbox Code Playgroud)
这就是我想要的,并且我认为ES6糖语法相当于上面(它不起作用......)
let foo = {
prop1: 'hello!',
prop2: null
}
const { prop1 = {} } = foo
const { prop2 = {} } = foo
console.log(prop1) // hello!
console.log(prop2) // null
Run Code Online (Sandbox Code Playgroud)
但不知何故,有时它似乎在React中工作,但其他时候它没有...它是兼容性问题吗?太混乱了!
javascript destructuring variable-assignment ecmascript-6 reactjs
class ProductsIndex extends Component {
constructor (props){
super(props);
console.log(this) // #1. this logs ProductsIndex component
fetch('someUrl')
.then(res => res.json())
.then(res => console.log(this)) // #2. this logs ProductsIndex component
fetch('someUrl')
.then(res => res.json())
.then(console.log) // #3. this logs [{..},{..},{..},{..}]
}
componentDidMount(){
fetch('someUrl')
.then(res => res.json())
.then(console.log) // #4. this logs [{..},{..},{..},{..}]
}
Run Code Online (Sandbox Code Playgroud)
如上面的代码所示,#1和#2都指向this。同样如图所示,#3和#4都返回相同的数组。但是,为什么下面的代码不起作用?
class ProductsIndex extends Component {
constructor (props){
super(props);
fetch('someUrl')
.then(res => res.json())
.then(arr => {
this.state = {
array: arr
}
})
}
Run Code Online (Sandbox Code Playgroud)
它抛出一个错误,说 …
我有我的rails应用程序并试图通过添加一个名为cancancan的gem制作的方法来添加权限.所以下面有两种方法.
def find_review
@review = Review.find(params[:id])
end
def authorize_user!
unless can? :manage, @review
redirect_to product_path(@review.product)
end
end
Run Code Online (Sandbox Code Playgroud)
有两种情况.案例1:调用destroy内部的方法动作
def destroy
find_review
authorize!
@product = @review.product
@reviews = @product.reviews
@review.destroy
end
Run Code Online (Sandbox Code Playgroud)
和案例2:使用before_action方法调用方法
before_action :find_review, :authorize!, only: [:destroy]
def destroy
@product = @review.product
@reviews = @product.reviews
@review.destroy
redirect_to product_path(@product), notice: 'Review is deleted'
end
Run Code Online (Sandbox Code Playgroud)
我使用before_action(案例2)甚至在调用操作之前重定向未经授权的用户,这样才有意义.我想知道的是在案例1中,为什么授权方法在销毁审核之前不会中断和重定向用户?它实际上重定向,但删除审查后.但我认为红宝石是同步的..
reactjs ×3
javascript ×2
asynchronous ×1
callback ×1
components ×1
ecmascript-6 ×1
es6-promise ×1
html ×1
js-beautify ×1
ruby ×1