React本机组件一经计算就不会更新
我在屏幕中有一个组件列表。每个组件都会对 useEffect 进行计算。我希望他们在完成每次计算后立即更新,但相反,它们会在所有计算完成后全部更新。
我做错了什么?
组件示例:
import React, {useEffect, useState} from 'react';
import {View, Text} from 'react-native';
const Teste = () => {
const Item = props => {
const [tempo, setTempo] = useState('calculando...');
useEffect(() => {
const inicio = new Date();
const rdm = Math.random();
sleep(rdm * 1000 + 2000);
setTempo(`${new Date() - inicio} millisegundos`);
}, []);
const sleep = milliseconds => {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
};
return (
<View style={{marginBottom: 20}}>
<Text>Item {props.nome}</Text>
<Text>Tempo - {tempo}</Text>
</View>
);
};
return (
<View style={{padding: 40}}>
<Item nome="1" />
<Item nome="2" />
<Item nome="3" />
</View>
);
};
export default Teste;
I have a list of components in a screen. Each component makes a calculation on useEffect. I expect then to update as soon as they finish each calculation, but instead they all update after all calculations completes.
What I'm doing wrong?
Example of component:
import React, {useEffect, useState} from 'react';
import {View, Text} from 'react-native';
const Teste = () => {
const Item = props => {
const [tempo, setTempo] = useState('calculando...');
useEffect(() => {
const inicio = new Date();
const rdm = Math.random();
sleep(rdm * 1000 + 2000);
setTempo(`${new Date() - inicio} millisegundos`);
}, []);
const sleep = milliseconds => {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
};
return (
<View style={{marginBottom: 20}}>
<Text>Item {props.nome}</Text>
<Text>Tempo - {tempo}</Text>
</View>
);
};
return (
<View style={{padding: 40}}>
<Item nome="1" />
<Item nome="2" />
<Item nome="3" />
</View>
);
};
export default Teste;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有两个问题...
睡眠
功能,我什至无法item
teste> teste
组件,这意味着每当teste
渲染器时,item
重新定义,我建议将
iteg> item
移出teste
,并使用基于承诺的 Sleep在这里
sleep> sleep()
返回两者,一旦超时到期,也可以解决一个诺言,以及如果您的组件已卸下,则可以取消延迟的函数。Two problems here...
sleep
function, I literally can't evenItem
component inside yourTeste
component which means wheneverTeste
renders,Item
is redefinedI suggest moving
Item
out ofTeste
and using a promise-based sleepHere
sleep()
returns both a promise that resolves once the timeout has expired as well as a function to cancel the delay if your component is unmounted.