[英]How to improve setting state in ReactJS?
I'm getting some info throw API which is set in state.我收到了一些信息,它设置在 state 中。 These info must be filtered depending on what I type in the input.这些信息必须根据我在输入中键入的内容进行过滤。 When i filter this array state and delete a letter from input I can not return my state to the previous value but if I type one more letter not the whole array is filtered.当我过滤这个数组 state 并从输入中删除一个字母时,我无法将我的 state 返回到以前的值,但是如果我再输入一个字母,则不会过滤整个数组。
I've tried to introduce a class property where all initial info is present and then to set state depending on filtered property.我尝试引入一个 class 属性,其中存在所有初始信息,然后根据过滤属性设置 state 。
js: js:
state = {
countries: [],
}
_allCountries = [];
componentDidMount() {
const { getData } = this.props;
getData()
.then(this.onCountryLoaded)
.catch(this.onError)
}
componentDidUpdate(prevProps) {
if (prevProps.matchPattern !== this.props.matchPattern) {
this.setState((_, props) => ({
countries : this._allCountries.filter(country => country.name.match(props.matchPattern))
}))
}
}
The thing I did works but I feel it's not the best approach.我所做的事情有效,但我觉得这不是最好的方法。 I think I need to use only countries state not the allCountries to filter countries.我想我只需要使用国家 state 而不是 allCountries 来过滤国家。
I would suggest such a way我会建议这样的方式
state = {
countries: [],
countriesFiltered: [];
}
if nothing is typed - just set countriesFiltered equal to country.如果没有输入 - 只需将 countriesFiltered 设置为国家。
If anything is typed - then assign filtered records to countriesFiltered.如果输入了任何内容 - 然后将过滤后的记录分配给 countryFiltered。
If new word includes the previous then no need to filter countries, you can filter countriesFiltered如果新词包含前一个则不需要过滤国家,您可以过滤国家过滤
And that is it.就是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.