首页 > 解决方案 > 为什么我的状态没有在 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" />;
}

标签: javascriptreactjsreact-hooks

解决方案


看来问题是由于您的状态传播不正确而引起的。

在父 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>;
};

推荐阅读