reactjs - 反应本机间隔状态不更新
问题描述
状态变化中的间隔功能不起作用请帮帮我。
状态不变
function Home({ route, navigation }) {
const [ marker, setMarker ] = useState(0);
_stropeText = () => {
if (marker == 0){
setMarker(marker => 1);
} else {
setMarker(marker => 0);
}
}
React.useEffect(() => {
setLoading(true);
const unsubscribe = navigation.addListener('focus', () => {
setInterval(_stropeText, 500);
});
return () => { };
}, [navigation]);
}
解决方案
您对值有一个闭包marker
,将其添加到useEffect
依赖数组中,或者使用带有useRef
钩子的引用。
此外,您将回调传递给useState
,它会进行功能更新,这不是这里的情况。
function Home({ route, navigation }) {
const [marker, setMarker] = useState(0);
React.useEffect(() => {
setLoading(true);
const _stropeText = () => {
if (marker === 0) {
setMarker(1);
} else {
setMarker(0);
}
};
const unsubscribe = navigation.addListener("focus", () => {
setInterval(_stropeText, 500);
});
return () => {
/*remove listener*/
};
}, [navigation, marker]);
}
推荐阅读
- python-3.x - 使用带有条件表达式的相关模型
- c++ - (SFML, C++) 如何在动态分配的 sf::VertexArray 中访问特定的 sf::Vertex?
- blazor-webassembly - 为 Raspberry Pi Docker Swarm 容器化托管的 Blazor WebAssembly
- sql-server - 10 和当前行之间的 T-SQL 行 - 应该返回 NULL 吗?
- variables - 如何在条件下使用作业之间传递的变量?
- arrays - 如何快速发布存储在 NSArray var 中的字典数组?
- python - 基于索引的多个列表到单个列表
- javascript - 类型 'undefined' 不能分配给类型 'xxx' 与 if else on 参数
- json - jq:对对象值进行排序
- java - add() 方法在 ArrayList 中的所有索引处保持写入相同的对象