Javascript 箭头函数不应返回赋值?
我的代码在应用程序中正常工作,但是,我的eslint不喜欢它,并说我不应该返回作业。这有什么问题Javascript 箭头函数不应返回赋值?,javascript,reactjs,eslint,Javascript,Reactjs,Eslint,我的代码在应用程序中正常工作,但是,我的eslint不喜欢它,并说我不应该返回作业。这有什么问题 <div ref={(el) => this.myCustomEl = el} /> this.myCustomEl=el}/> 您隐式返回了一个赋值this.myCustomEl=el是一项分配。您可以通过将箭头函数更改为(el)=>{this.myCustomEl=el}来修复此linting错误,该函数不再隐式返回,因为您将其包装在{}中,而不是() 旁注:在渲染方法中内联
<div ref={(el) => this.myCustomEl = el} />
this.myCustomEl=el}/>
您隐式返回了一个赋值this.myCustomEl=el
是一项分配。您可以通过将箭头函数更改为(el)=>{this.myCustomEl=el}
来修复此linting错误,该函数不再隐式返回,因为您将其包装在{}
中,而不是()
旁注:在渲染方法中内联声明箭头函数将破坏PureComponent
,因为每次组件渲染时,它都必须声明一个新的匿名函数,因此PureComponent
所做的浅层道具比较将被打破,并将始终重新渲染
尝试将其作为组件的一种方法
class MyClass extends React.PureComponent {
getRef = (el) => { this.ref = el; }
render() {
return <div ref={this.getRef} />;
}
}
类MyClass扩展了React.PureComponent{
getRef=(el)=>{this.ref=el;}
render(){
返回;
}
}
如果上述语法不适用,可以使用以下语法:
class MyClass extends React.PureComponent {
constructor(props) {
super(props);
this.ref = null;
this.getRef = this.getRef.bind(this);
}
getRef(el) {
this.ref = el;
}
render() {
return <div ref={this.getRef} />;
}
}
类MyClass扩展了React.PureComponent{
建造师(道具){
超级(道具);
this.ref=null;
this.getRef=this.getRef.bind(this);
}
getRef(el){
this.ref=el;
}
render(){
返回;
}
}
修复程序:
<div ref={(el) => { this.myCustomEl = el }} />
在上述情况下,编译器警告是有意义的,因为k=true
的计算结果为true(而不是k===true
,这可能是您想要键入的内容),并导致意外行为。因此,当您返回赋值时,eshint会注意到,假定您打算返回比较,并让您知道应该小心
在您的例子中,您可以通过简单地不返回结果来解决这个问题,这是通过添加封闭括号{}和no return语句来完成的:
<div ref={(el) => { this.myCustomEl = el }} />
{this.myCustomEl=el}}/>
您还可以调整eshint警告,如下所示:
我只是想记下我遇到的一些事情。我安装了Prettier,它不断地拿走我的parens,导致eslint错误: 为了证实这一点,我添加了一个更漂亮的忽略:
<div>
{/*prettier-ignore*/}
<Map
ref={(m) => {
this.leafletMap = m;
}}
center={mapCenter}
zoom={zoomLevel}
>
<TileLayer
attribution={stamenTonerAttr}
url={stamenTonerTiles}
/>
</Map>
</div>
{/*更漂亮的忽略*/}
{
这个.map=m;
}}
中心={mapCenter}
zoom={zoomLevel}
>
在其周围添加{}
警告,请尝试(this.myCustomEl=el)}/>
相同的警告。虽然这是一个警告,但我无法通过带有警告的测试。{this.myCustomEl=e}l}/>
@epascarello typo with the e}l?仅供参考,此错误w“无法读取未定义的属性'appendChild'”您可以看到它在这种情况下工作。
<div ref={(el) => { this.myCustomEl = el }} />
<div>
{/*prettier-ignore*/}
<Map
ref={(m) => {
this.leafletMap = m;
}}
center={mapCenter}
zoom={zoomLevel}
>
<TileLayer
attribution={stamenTonerAttr}
url={stamenTonerTiles}
/>
</Map>
</div>