[英]React Eslint destructuring-assignment
I am using eslint rule react/destructuring-assignment
which throws. 我正在使用eslint规则
react/destructuring-assignment
。 How can I destructure this? 我该如何破坏它?
getStuff(model = this.state.model) {
// some stuff
}
ESLINT doesn't allow to use this.state.model
and it suggests you to utilize destructuring: ESLINT不允许使用
this.state.model
,它建议您利用解构:
const { model: stateModel } = this.state
getStuff(model = stateModel) {
But, I'm afraid as it's inside react class component. 但是,我担心它是在React类组件内部。 Thus, you can't define a const or var before method definition.
因此,您不能在方法定义之前定义const或var。 You should disable the eslint for the line:
您应该禁用该行的eslint:
getStuff(model = this.state.model) { // eslint-disable-line
Alternatively, you may use like: 或者,您可以这样使用:
getStuff(model) {
const { model: stateModel } = this.state
const passedModel = model ? model : stateModel
// then work through passedModel
}
Hmm, I can think of this should do the trick: 嗯,我可以想到这应该可以解决问题:
getStuff({state: {model}} = this) {
But, frankly I have never used such. 但是,坦率地说,我从未使用过这种方法。 Just try and let me know.
请尝试让我知道。
Update : 更新 :
You may also use like: 您也可以这样使用:
getStuff(model) {
const { model: stateModel } = this.state || { model: model }
console.log(stateModel)
Or, simply: 或者,简单地:
getStuff(model) {
const { model } = this.state || { model }
// ----------------- similar to { model: model }
console.log(model)
As I understand your need, you want to have a default var for a model from state and be able to pass it also if needed. 据我了解您的需求,您想要一个来自状态的模型的默认变量,并在需要时也可以传递它。
getStuff(passedModel) {
const { model } = this.state
const toUseModelInMethod = passedModel || model
// or
const toUseModelInMethod = passedModel ? passedModel : model
}
If you just want to get the model from this.state it's simple 如果您只想从this.state获取模型,那很简单
getStuff() {
const { model } - this.state
}
Also you can pass your state to the method 您也可以将状态传递给方法
getStuff({ model }) {...}
this.getStuff(this.state) // linter is not happy
// that's is better
getStuff(model){...}
const { model } = this.state
this.getStuff(model)
Your example isn't destructuring. 您的例子不是破坏性的。 A function would look like this:
函数看起来像这样:
function getStuff({ property1, property2 }) {
...
}
The above example would pull property1 and property2 from whatever object is passed to the given function. 上面的示例将从任何传递给给定函数的对象中提取property1和property2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.