【发布时间】:2021-12-17 14:33:35
【问题描述】:
(对不起,我的英语,我使用谷歌翻译)在我的代码中,我有几个迭代,在每个迭代中,我都会更改要在屏幕上显示的文本:
export function MyScreen() {
const [currentText, setCurrentText] = useState('');
async function sync() {
setCurrentText('Sending configs')
await ConfigurationService.sync();
setCurrentText('Sending clients')
await ClientService.sync();
setCurrentText('Fetching data for local sync')
await api.get('http://myserver/get').then(async ({ data }) => {
await syncClients(data);
await syncProducts(data);
//... call from other functions that also change setCurrentText
setCurrentText('Sync finished');
return true;
})
.catch(error => {
setCurrentText('Sync failed');
return false;
});
}
async function syncClients(data) {
setCurrentText('Sync local clients');
// data.clients.new, data.clients.updated and data.clients.excluded is a long array
if (data.clients) {
if (data.clients.new) {
setCurrentText(`Updating ${data.clients.new.length} clients`);
for (let client of data.clients.new) {
ClientRepository.save(client);
}
}
if (data.clients.updated) {
setCurrentText(`Updating ${data.clients.updated.length} clients`);
for (let client of data.clients.updated) {
ClientRepository.save(client );
}
}
if (data.clients.excluded) {
setCurrentText(`Excluding ${data.clients.excluded.length} clients`);
for (let client of data.clients.excluded) {
ClientRepository.delete(client);
}
}
}
}
async function syncProducts(data) {
setCurrentText('Sync local products');
// data.products.new, data.products.updated and data.products.excluded is a long array
if (data.products) {
if (data.products.new) {
setCurrentText(`Saving ${data.products.new.length} products`);
for (let product of data.products.new) {
ProductRepository.save(product);
}
}
if (data.products.updated) {
setCurrentText(`Updating ${data.products.updated.length} products`);
for (let product of data.products.updated) {
ProductRepository.save(product);
}
}
if (data.products.excluded) {
setCurrentText(`Excluding ${data.products.excluded.length} products`);
for (let product of data.products.excluded) {
ProductRepository.delete(product);
}
}
}
}
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<TouchableOpacity onPress={sync}>
<Text>PRESS TO SYNC</Text>
</TouchableOpacity>
<Text>{currentText}</Text>
</View
);
}
事实证明 currentText 变量只更新了前 3 次,然后它已经更新了最后一个文本“同步完成”。在其他功能中触发的更新不会更新屏幕。 有没有人经历过这种情况?
【问题讨论】:
标签: reactjs react-native react-hooks