为什么在useEffect中我的状态不更新?

时间:2019-11-26 12:30:39

标签: javascript reactjs react-hooks

我正在尝试通过编写一个小的计数器程序来学习反应挂钩,遇到以下问题。

在下面的组件中,我将传递计数器和增量作为分别具有默认值0和1的道具。我想在组件安装时设置一个计时器,该计时器将每秒更新一次计数器,因为counter = counter + increment。增量状态每隔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" />;
}

1 个答案:

答案 0 :(得分:2)

问题似乎是由于您的状态分布不正确引起的。

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