为什么即使使用useCallback后状态也始终为0

时间:2019-05-05 11:55:07

标签: javascript reactjs react-hooks

我希望它应该是一个时间计数器。 useCallback将在时间更改后刷新,因此第二次时间将为1, 但仍然是0

我尝试使用useCallback,但是没用

import React, { useState, useEffect, useCallback } from 'react';
import { render } from 'react-dom';
import './style.css';

import {interval} from 'rxjs'
import { take } from 'rxjs/operators';

const inter$ = interval(1000);

function App(){
  const [time, setTime] = useState(0);
  const callback = useCallback(()=> {
      setTime(time+1);
      console.log('hella');
    }, [time])

  useEffect(()=>{
    console.log('hello')
    inter$.subscribe(callback)

  }, [])

  return <div>{time}</div>
}


render(<App />, document.getElementById('root'));

始终显示1

这是code

2 个答案:

答案 0 :(得分:2)

useEffect内部,回调没有改变,因为它不是依赖项。因此,订阅回调中的时间始终为0。

使用Rx.js的解决方案:
setTime调用基于回调函数中的prevState。

import React, { useState, useEffect } from "react";
import { render } from "react-dom";
import "./style.css";

import { interval } from "rxjs";
import { take } from "rxjs/operators";

const inter$ = interval(1000);

function App() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    console.log("hello");
    inter$.subscribe(() => {
      setTime(prevTime => prevTime + 1);
      console.log("hella");
    });
  }, []);

  return <div>{time}</div>;
}

render(<App />, document.getElementById("root"));

答案 1 :(得分:1)

更改setTime(time + 1);设置为setTime(time => time + 1); 这是完整的代码:

import React, { useState, useEffect, useCallback } from 'react';
import { render } from 'react-dom';
import './style.css';

import {interval} from 'rxjs'
import { take } from 'rxjs/operators';

const inter$ = interval(1000);

function App(){
  const [time, setTime] = useState(0);
  const callback = useCallback(()=> {
      setTime(time=>time+1);
      console.log('hella');
    }, [time])

  useEffect(()=>{
    console.log('hello')
    inter$.subscribe(callback)

  }, [])

  return <div>{time}</div>
}



render(<App />, document.getElementById('root'));

stackblitz