我有一个项目的平面清单,旁边有一个“删除”按钮。
当我单击删除按钮时,我能够从后端删除该项目,但实际的列表项目并未从视图中删除。
我正在使用useState挂钩,据我了解,组件在setState发生后会重新渲染。
setState函数用于更新状态。它接受一个新的 状态值,并重新渲染组件。 https://reactjs.org/docs/hooks-reference.html
状态设置和呈现方式我缺少什么?
出于各种原因,我不想使用useEffect侦听器。我希望组件在位置状态更新时重新呈现....我很确定正在与其他setStates一起发生....不确定我是否完全缺少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);
};
答案 0 :(得分:1)
这归结为更改相同的locations
数组并再次调用同一数组的setState
,这意味着作为纯组件的FlatList
将不会重新呈现,因为locations
的标识未更改。您可以先将locations
数组复制到newLocationsArray
(与newLocationNameArray
相似)来避免这种情况。
var newLocationsArray = locations.slice();
var newLocationNameArray = locationsNames.slice();