React Native State Management 问题 - useState hook 何时加载?



我有一个项目平面列表,旁边有一个"删除"按钮。

当我单击删除按钮时,我可以从后端删除该项目,但实际的列表项不会从视图中删除。

我正在使用useState钩子,据我了解,组件在setState发生后重新渲染。

setState 函数用于更新状态。它接受一个新的 状态值,并将组件的重新呈现排队。 https://reactjs.org/docs/hooks-reference.html

状态的设置和渲染方式缺少什么?

由于各种原因,我不想使用 useEffect 侦听器。我希望组件在位置状态更新时重新渲染....我很确定我的其他设置正在发生这种情况......不确定我是否完全错过了 setState 一直在做什么的标记,或者它是否是关于 setLocations(( 的特定内容。

const [locations, setLocations] = useState(state.infoData.locations);
const [locationsNames, setLocationsNames] = useState(state.infoData.names]);
...
const removeLocationItemFromList = (item) => {
var newLocationsArray = locations;
var newLocationNameArray = locationsNames;
for(l in locations){
if(locations[l].name == item){
newLocationsArray.splice(l, 1);
newLocationNameArray.splice(l, 1);
} else {
console.log('false');
}
}
setLocationsNames(newLocationNameArray); 
setLocations(newLocationsArray);
};
...
<FlatList style={{borderColor: 'black', fontSize: 16}} 
data={locationNames} 
renderItem={({ item }) => 
<LocationItem
onRemove={() => removeLocationItemFromList(item)}
title={item}/> } 
keyExtractor={item => item}/>

更新循环

const removeLocationItemFromList = (item) => {
var spliceNewLocationArray =locations;
var spliceNewLocationNameArray = locationsNames;
for(f in spliceNewLocationArray){
if(spliceNewLocationArray[f].name == item){
spliceNewLocationArray.splice(f, 1);
} else {
console.log('false');
}
}
for(f in spliceNewLocationNameArray){
if(spliceNewLocationNameArray[f] == item){
spliceNewLocationNameArray.splice(f, 1);
} else {
console.log('false');
}
}
var thirdTimesACharmName = spliceNewLocationNameArray;
var thirdTimesACharmLoc = spliceNewLocationArray;
console.log('thirdTimesACharmName:: ' + thirdTimesACharmName + ', thirdTimesACharmLoc::: ' + JSON.stringify(thirdTimesACharmLoc)); // I can see from this log that the data is correct
setLocationsNames(thirdTimesACharmName); 
setLocations(thirdTimesACharmLoc);
};

这归结为改变相同的locations数组并再次使用相同的数组调用setState,这意味着作为纯组件的FlatList不会重新渲染,因为locations的身份没有改变。您可以先将locations数组复制到newLocationsArray(与newLocationNameArray类似(以避免这种情况。

var newLocationsArray = locations.slice();
var newLocationNameArray = locationsNames.slice();

最新更新