react的state如何不全量更新

react中在监听输入框的值时,页面内使用的随机图片会变动

在每次输入框输入的时候,背景图都会变化,但我期待的场景是,每次页面刷新后背景图随机变,其他时候不变

这是输入框发生变化后将值赋给value
 <Search
                    value={inputValue}
                    onChange={(e: any) => {
                        let value = e.target.value;
                        setInputValue(value);
                    }}
                />
这里遍历数据,使用随机背景图
 {
                            typeList.map((item: any) => (
                                <SwiperSlide
                                   style={{ backgroundImage: `url(${require(`@assets/images/supervisor/type_back_0${Math.floor(Math.random() * 8) + 1}.png`)}` }}
                                >
                                </SwiperSlide>
                            ))
                        }


const [backgrounds, setBackgrounds] = useState<string[]>([]);

useEffect(() => {
  const backgrounds = typeList.map(() => 
    require(`@assets/images/supervisor/type_back_0${Math.floor(Math.random() * 8) + 1}.png`)
  );
  setBackgrounds(backgrounds);
}, []);

{
  typeList.map((item: any, index: number) => (
    <SwiperSlide
      style={{ backgroundImage: `url(${backgrounds[index]})` }}
    >
    </SwiperSlide>
  ))
}

如果你希望背景图片在页面刷新时随机变化,可以在设置SwiperSlide的style属性之前,预先生成随机背景图片的索引,并将其作为变量存储在state中,如:

const [bgIndex, setBgIndex] = useState(Math.floor(Math.random() * 8) + 1)

...

{typeList.map((item: any) => (
  <SwiperSlide
    style={{
      backgroundImage: `url(${require(`@assets/images/supervisor/type_back_0${bgIndex}.png`)})`
    }}
  />
))}


这样,每次页面刷新后背景图片随机变化,并且其他时候不会变化。如果你需要在页面刷新时随机更新背景图片,可以在使用useEffect的时候通过配置第二个参数来实现:

useEffect(() => {
  setBgIndex(Math.floor(Math.random() * 8) + 1)
}, [])

这样每次页面刷新时都会重新生成随机背景图片。以上是React中实现只在页面刷新时随机更新背景图片的要求。