gpt4 book ai didi

javascript - 为什么我的状态没有在 useEffect 中更新?

转载 作者:行者123 更新时间:2023-11-29 10:55:10 26 4
gpt4 key购买 nike

我正在尝试通过制作一个小计数器程序来学习 React Hooks,我遇到了以下问题。

在下面的组件中,我将 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>;
};

关于javascript - 为什么我的状态没有在 useEffect 中更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59051042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com