简体   繁体   English

3 state 的 React Native 许多重新渲染错误

[英]React Native many re-renders error for 3 state

Error: Too many re-renders.错误:重新渲染过多。 React limits the number of renders to prevent an infinite loop. React 限制了渲染的数量以防止无限循环。 My goal is to keep citydata fresh as countries are updated.我的目标是在更新国家/地区时保持城市数据的新鲜度。 I get this error how fix it in this code?我收到此错误如何在此代码中修复它?

 const [selectedCity, setSelectedCity] = useState({}) const [selectedCountry, setSelectedCountry] = useState({}) const [cityData,setCityData]= useState(TurkeyCityData) function onChangeCity() { return (val) => setSelectedCity(val) } function onChangeCountry() { setCityData(`${selectedCountry.item}${'CityData'}`) return (val)=>setSelectedCountry(val); } //`${selectedCountry.item}${'CityData'}` return ( <View style={styles.container}> <View style={styles.header}> <SelectBox label='' options={countryData} value={selectedCountry} onChange={onChangeCountry()} hideInputFilter={false} width={width/2.5} containerStyle={styles.selectbox} arrowIconColor='#5359d1' searchIconColor='#5359d1' inputPlaceholder='Ülke Seç' />

In the linked example you shared, the handler code is:在您共享的链接示例中,处理程序代码是:

function onChange() {
  return (val) => setSelectedTeam(val)
}

This returns a state-setting function that is used as the change handler with onChange={onChange()} .这将返回一个状态设置 function 用作onChange={onChange()}的更改处理程序。

In your code, you return a handler as they do, but you also set state immediately:在您的代码中,您像他们一样返回一个处理程序,但您也立即设置 state :

function onChangeCountry() {
  setCityData(`${selectedCountry.item}${'CityData'}`) // <-- triggers rerender
  return (val)=>setSelectedCountry(val);
}

There has to be some condition or trigger mechanism for any state sets or you'll get an infinite rerendering loop.任何 state 集都必须有一些条件或触发机制,否则您将获得无限的重新渲染循环。 You can use an effect or put the setter inside the handler callback, whichever makes more sense for your application logic:您可以使用效果或将 setter 放在处理程序回调中,这对您的应用程序逻辑更有意义:

function onChangeCountry() {
  return val => {
    setSelectedCountry(val);
    setCityData(`${selectedCountry.item}${'CityData'}`);
  };
}

As an aside, I'm not sure if the extra layer of abstraction makes much sense here;顺便说一句,我不确定额外的抽象层在这里是否有意义。 I'd just use one function which is less confusing:我只使用一个 function 不太容易混淆:

function onChangeCountry(val) {
  setSelectedCountry(val);
  setCityData(`${selectedCountry.item}${'CityData'}`);
}

and use it with:并将其用于:

onChange={onChangeCountry}

Or, rename the function makeOnChangeCountryHandler() so it's clear that the function isn't the handler itself;或者,将 function makeOnChangeCountryHandler()重命名,以便清楚地表明 function 不是处理程序本身; rather, it returns/creates/makes the handler upon invocation.相反,它在调用时返回/创建/制作处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM