reactjs - 在另一个函数中访问状态值 - useState
问题描述
如何访问状态的更新值?我在 UI 上获得了更新的值,但在动态访问状态值时却没有。
const OTP = () => {
const [counter, setCounter] = useState(3);
const [someState, setSomeState] = useState("something");
useEffect(() => {
startCountdownTimer();
}, []);
const countdownTimerFunc = () => {
let value = counter; // <--- initial value always
// someState <--- initial value always
console.log('==== countdown: START====', counter);
if (value && value > 0) {
setCounter(prev => prev - 1); // Updating right value
} else {
console.log('==== countdown: STOP====');
}
};
const startCountdownTimer = () => {
setSomeState("updated something");
internalID = BackgroundTimer.setInterval(() => {
countdownTimerFunc();
}, 1000);
};
const counterUI = () => {
return (
<Text>{counter}</Text>
)
}
...
return (
<View>
{counterUI()}
</View>
)
};
export default OTP;
更新:访问状态的正确结构是什么?是仅使用 useEffect 还是我们可以使用返回状态的自定义钩子来处理?在我的结构中看到访问单独函数中的值的困难。
解决方案
请替换以下代码并告诉我
const OTP = () => {
const [counter, setCounter] = useState(3);
const [someState, setSomeState] = useState("something");
useEffect(() => {
if (counter > 0) {
countdownTimerFunc()
}else{
startCountdownTimer();
}
}, [counter]);
const countdownTimerFunc = () => {
let value = counter; // <--- initial value always
// someState <--- initial value always
console.log('==== countdown: START====', counter);
if (value && value > 0) {
setCounter(counter - 1); // Updating right value
} else {
console.log('==== countdown: STOP====');
}
};
const startCountdownTimer = () => {
setSomeState("updated something");
setTimeout(() => {
countdownTimerFunc();
}, 1000);
};
const counterUI = () => {
return (
<Text>{counter}</Text>
)
}
...
return (
<View>
{counterUI()}
</View>
)
};
export default OTP;
推荐阅读
- javascript - 链接样式表后 CSS/JS 动画不起作用
- database - 对象名称作为 Logtalk 中的变量
- sql - 不同 ID 的最旧记录 - SparkSQL
- html - Angular throws ExpressionChangedAfterItHasBeenCheckedError
- javascript - 使用 jQuery 隐藏除给定 data-* 属性之外的所有元素
- javascript - 从样板(React)项目中删除服务器端
- python - Python Pandas - 模糊重复匹配
- php - 在简单的 mvc 项目中无法使用 htaccess
- php - 如何在 laravel 中获得产品的经过验证的评论
- javascript - Datatable 插件中的动态下拉菜单