嗨,我是ReactJs的新开发人员。我对useEffect渲染有问题。我有一个例子,我试图随着时间改变背景图像,但是useEffect使得渲染如此之多,而我的背景图像却随着时间而循环。我只想按顺序更改图像,例如bg1 bg2 bg3等。 如何解决这个无限渲染?
我的示例.tsx
import React, { useEffect, useState } from 'react';
import { connect } from "../../../store/store";
const LeftPart = (props: any) => {
const [value, setValue] = useState(1);
const {loginLeftImagesLength} = props;
const changeLeftBackgroungImage : any = () =>{
const interval = setInterval(() => {
if (value <= loginLeftImagesLength.payload) {
setValue(value+1);
} else{
setValue(1);
}
}, 3000);
return () => clearInterval(interval);
};
useEffect(() => {
changeLeftBackgroungImage();
});
return (
<div className="col-xl-7 col-lg-7 col-md-7 col-sm col-12">
<img id="image" src={"../../../assets/images/bg"+value+".jpg"} style={{ width: "100%", height: "99vh" }} alt="Login Images"></img>
</div >
)
}
export default connect((store: any) => ({ loginLeftImagesLength: store.loginLeftImagesLength }))(LeftPart) as any;
答案 0 :(得分:0)
您有无限渲染,因为您没有在Stream<Integer>
中指定任何依赖项
private static void AddJsonFormatterServices(IServiceCollection services) {
services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<MvcNewtonsoftJsonOptions>, OurMvcJsonOptions>());
}
您也可以通过这种方式完成
private static void AddJsonFormatterServices(IServiceCollection services) {
services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<MvcNewtonsoftJsonOptions>, OurMvcJsonOptions>());
services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<OurSpecializedMvcJsonOptions>, OurSpecializedMvcJsonOptions>());
}
答案 1 :(得分:0)
为什么不将整个代码放在useEffect挂钩中。
useEffect(() => ) {
const {loginLeftImagesLength} = props;
const changeLeftBackgroungImage : any = () =>{
const interval = setInterval(() => {
if (value <= loginLeftImagesLength.payload) {
setValue(value+1);
} else{
setValue(1);
}
}, 3000);
return () => clearInterval(interval);
};[changeBGStateHere])
使用if else语句更改背景...
如果(值=== 1){
changeLeftBackgroungImage();
} else(值=== 2){
以此类推。
Let the interval change the state and let useEffect rerender when the state for the time changes.