javascript - Double setState method in one function -
i trying create autocomplete component. it's input user types countru name , if letters match name of country, hints displayed. in app component have method handlechange within method change state 2 times, bad idea. how can split change state in distinct methods ?
import react, { component } 'react'; import autocomplete './autocomplete.jsx'; import data './data.json'; class app extends component { constructor(props) { super(props); this.state = { inputvalue: '', resoults: [] } } handlechange() { let inputvalue = this.refs.input.value; this.setstate({ inputvalue: inputvalue }); let regular = "^" + this.state.inputvalue; let reg = new regexp(regular , "i"); let filtered = data.filter((i,index)=> { return (reg.test(i.name) ); }); console.log(filtered); this.setstate({resoults:filtered}) } render() { return ( <div> <input onchange={this.handlechange.bind(this)} type="text" ref="input"/> <h3>you typed: {this.state.inputvalue}</h3> <autocomplete resoults={this.state.resoults} /> </div> ); } } export default app; import react, {component} 'react'; class autocomplete extends component { render() { return ( <div> <h4>autocompletecomponent</h4> {this.props.resoults.map((i)=> { return ( <ul> <li>{i.name}</li> </ul> ); })} </div> ); } } export default autocomplete;
i found myself in position many times, got conclusion it's better compute autocomplete options (in case) without having them in state of component.
as have used them until now, state , props of component should represent minimal data needed render specific component. since have input value in state, having autocomplete options there seems redundant me. here propose:
class app extends component { this.state = { inputvalue: '', }; handlechange(e) { const inputvalue = e.target.value; this.setstate({ inputvalue, }); } computeresults() { const {inputvalue} = this.state; // functionality computing results here } render() { const {inputvalue} = this.state; const results = this.computeresults(); return ( <div> <input type="text" onchange={this.handlechange.bind(this)} value={inputvalue} /> <h2>you typed: {inputvalue}</h2> <autocomplete results={results} /> </div> ); } } notes
- since results come synchronously, via
.jsonimport, seems perfect solution me. if want them viafetchor else, you'll have figure out different approach, keep in mind state of component should not contain redundant data. - stop using
refstringvalue! , userefs when there absolutely no other way because react component should not deal dom operations directly. if need userefs, userefcallbacks.
hope helps!
Comments
Post a Comment