javascript - 为什么我的状态没有在 useEffect 中更新?
问题描述
我正在尝试通过制作一个小型计数器程序来学习反应钩子,我遇到了以下问题。
在下面的组件中,我将 counter 和 increment 作为 props 分别传递默认值 0 和 1。我想在组件安装时设置一个计时器,它将每秒更新一次计数器,计数器 = 计数器 + 增量。增量状态每 5 秒从父组件更改一次。
import React from "react";
import { useEffect, useState } from "react";
export default function AppHook(props) {
let [counter, setCounter] = useState(props.counter);
let [increment, setincrement] = useState(props.increment);
useEffect(() => {
setincrement(props.increment);
}, [props.increment]);
// run only once.
// here my increment value is always 1 even if the upper hook updates
// it whenever parent changes it. Why is this happening?
useEffect(() => {
console.log("component did mount");
setInterval(() => {
setCounter(counter => counter + increment);
}, 1000);
}, []);
return <div className="AppHook" />;
}
解决方案
看来问题是由于您的状态传播不正确而引起的。
在父 JS 中:
import React, { useState, useEffect, Fragment } from 'react';
import AppHook from './AppHook';
const ParentApp = props => {
const [counter, setCounter] = useState(0);
const [increment, setIncrement] = useState(1);
useEffect(() => {
setInterval(setIncrement(increment++), 5000);
}, []);
return (
<Fragment>
Increment is {increment}
Counter is <AppHook counter={counter} setCounter={setCounter} increment={increment} />
</Fragment>
);
};
在 Child.js (apphook.js) 中:
import React, { useState, useEffect, Fragment } from 'react';
const AppHook = props => {
const { counter, setCounter, increment } = props;
useEffect(() => {
setInterval(setCounter(increment), 1000);
}, []);
return <Fragment> {counter} </Fragment>;
};
推荐阅读
- reactjs - 在反应中使用 redux-thunk 初始化单个计时器
- java - 协助编写构造函数
- node.js - 如何从函数将响应发送回 nodejs 中的邮递员?
- unicode - 为什么嘊字符的 URL 编码为 %E5%98%8A?
- javascript - 如何在循环中返回函数(for .. of ..)javascript?
- maven - 防止在项目中使用junit4库
- firefox - Firefox 附加组件:存储随时间变化的数组的最佳方式是什么?
- uml - BoUML 的状态机生成器在退出 StateMachine 状态之前调用 doActivity 是否正确?
- react-native - 如何使用 Keycloak IAM 响应使用 Expo 创建的本机应用程序?
- c# - Elastic search 2.0 搜索类似查询