[英]why state always be 0, even after using useCallback
I expect it should be a time counter. 我希望这应该是一个时间计数器。 useCallback will refresh after the time change, so time will be 1 in the second time, but still is 0 useCallback将在时间更改后刷新,因此第二次时间将为1,但仍为0
I tried to use useCallback but didn't work 我尝试使用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'));
always show 1 总是显示1
Inside useEffect
the callback doesn't change since it's not a dependency. 在useEffect
内部,回调没有改变,因为它不是依赖项。 Thus, the time inside the subscription callback is always 0. 因此,订阅回调内部的时间始终为0。
Working solution with Rx.js
: 使用Rx.js
工作解决方案:
setTime
call is based on prevState inside callback function. 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"));
change setTime(time+1); 更改setTime(time + 1); to setTime(time=>time+1); 设置为setTime(time => time + 1); Heres the full code : 这是完整的代码:
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'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.