在我的课堂上,eslint 抱怨“预期‘this’被类方法‘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>
);
}
}
解决这个问题或重构这个组件的最佳方法是什么?
原文由 Hinesh Patel 发布,翻译遵循 CC BY-SA 4.0 许可协议
您应该将函数绑定到
this
正如 ESLint 错误所说"Expected 'this' to be used by class method 'getUrlParams'
因为你在渲染过程中没有使用
getUrlParams
(比如onClick()
)所以上面的技术很好,我们可以称之为“在类属性中使用箭头函数”。还有其他绑定方式:
this.getUrlParams=this.getUrlParams.bind(this)
onClick={()=>this.getUrlParams()}
假定该函数没有参数。React.createClass
这对于 ES6 没有意义 :)