Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  146] [ 4]  / answers: 1 / hits: 133943  / 7 Years ago, mon, may 29, 2017, 12:00:00

In my class, eslint is complaining Expected 'this' to be used by class method 'getUrlParams'



Here is my class:



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>
);
}
}


What is the best approach to solve this or refactor this component?


More From » reactjs

 Answers
110

you should bind the function to this as the ESLint error says Expected 'this' to be used by class method 'getUrlParams'



getUrlParams = (queryString) => { .... }


as you are not using getUrlParams during render (like onClick()) so the above technique is good which we can call it usage of arrow function in class property.



there are other ways of binding too:




  • binding in constructor this.getUrlParams=this.getUrlParams.bind(this)

  • arrow function in render e.g.onClick={()=>this.getUrlParams()} assumed that function does not have params.

  • and React.createClass which with ES6 does not make sense :)


[#57629] Friday, May 26, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anais

Total Points: 672
Total Questions: 118
Total Answers: 121

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;