Hin*_*tel 42 javascript ecmascript-6 reactjs eslint
在我的课堂上,eslint抱怨"预期'这个'被类方法'getUrlParams'使用
这是我的班级:
class PostSearch extends React.Component {
constructor(props) {
super(props);
this.getSearchResults();
}
getUrlParams(queryString) {
const hashes = queryString.slice(queryString.indexOf('?') + 1).split('&');
const params = {};
hashes.forEach((hash) => {
const [key, val] = hash.split('=');
params[key] = decodeURIComponent(val);
});
return params;
}
getSearchResults() {
const { terms, category } = this.getUrlParams(this.props.location.search);
this.props.dispatch(Actions.fetchPostsSearchResults(terms, category));
}
render() {
return (
<div>
<HorizontalLine />
<div className="container">
<Col md={9} xs={12}>
<h1 className="aboutHeader">Test</h1>
</Col>
<Col md={3} xs={12}>
<SideBar />
</Col>
</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
解决此问题或重构此组件的最佳方法是什么?
Ami*_*avi 26
你应该将函数绑定到thisESLint错误中"Expected 'this' to be used by class method 'getUrlParams'
getUrlParams = (queryString) => { .... }
Run Code Online (Sandbox Code Playgroud)
因为你getUrlParams在渲染期间没有使用(比如onClick()),所以上面的技术很好,我们可以称之为"类属性中箭头函数的使用".
还有其他绑定方式:
this.getUrlParams=this.getUrlParams.bind(this)onClick={()=>this.getUrlParams()}假设函数没有参数.React.createClass与ES6没有意义:)Ioa*_*oan 16
这是一个ESlint规则,请参阅class-methods-use-this.
您可以提取方法getUrlParams并将其放入帮助程序或制作它static.
你还可以做的是移动this.props.location.search方法内部,因此调用this.getUrlParams()没有参数的方法,因为它似乎只使用它一次.
因此,这可能看起来像:
getUrlParams() {
const queryString = this.props.location.search;
...
return params;
}
Run Code Online (Sandbox Code Playgroud)
最后一个选项是禁用此ESlint规则.
rfd*_*fdc 10
getUrlParams = queryString => { ... }
Run Code Online (Sandbox Code Playgroud)
我的解决方案是在类之外使用此函数并将此函数绑定到类。
function getUrlParams(queryString) {
const hashes = queryString.slice(queryString.indexOf('?') + 1).split('&');
const params = {};
hashes.forEach((hash) => {
const [key, val] = hash.split('=');
params[key] = decodeURIComponent(val);
});
return params;
}
class PostSearch extends React.Component {
constructor(props) {
super(props);
this.getSearchResults();
this.getUrlParams = getUrlParams.bind(this); // add this
}
getSearchResults() {
const { terms, category } = this.getUrlParams(this.props.location.search);
this.props.dispatch(Actions.fetchPostsSearchResults(terms, category));
}
render() {
return ( "bla bla" );
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41292 次 |
| 最近记录: |