react-activation icon indicating copy to clipboard operation
react-activation copied to clipboard

KeepAlive内部组件切换页面时,组件的输入状态无法缓存

Open coderyxn507 opened this issue 3 years ago • 3 comments
trafficstars

keepalive组件包裹了一个A组件,A组件可以渲染B组件或者C组件,在切换渲染的时候B、C会有一个输入框,切换状态时输入框的输入状态会丢失。但是做路由切换的时候、输入状态不会被清空。请问大佬们,这个问题该怎么解决啊? image

image image image

coderyxn507 avatar Aug 05 '22 14:08 coderyxn507

你是想让内部的 input 不要缓存吗?可以使用 keep alive 的生命周期钩子来监听某个区域进入缓存的状态,根据这个状态来手动卸载你不想缓存的组件

import { useActivate, useUnactivate } from 'react-activation'

function Inner() {
  return <input />
}

function Page() {
  const [cached, setCached] = useState(false)

  useActivate(() => setCached(false))
  useUnactivate(() => setCached(true))

  return (
    <>
      <input />
      {!cached && <Inner />
    </>
  )
}

export default function Comp() {
  return <KeepAlive><Page /></KeepAlive>
}

CJY0208 avatar Aug 08 '22 05:08 CJY0208

不好意思,可能我没描述清楚。我想让内部的input缓存上数据,但是在条件渲染时,切换展示了不同组件后,input缓存的数据会丢失。例如:

const Component = (isShow) => {
  if (isShow) {
    return (
      <div title="页面1">
        <Input />
      </div>
    );
  }

  return (
    <div title="页面2">
      <Input />
    </div>
  );
};

coderyxn507 avatar Aug 08 '22 09:08 coderyxn507

那你需要对这个 Input 也做 Keep 处理,注意 cacheKey 要相同,表明是同一份缓存


const Component = (isShow) => {
  if (isShow) {
    return (
      <div title="页面1">
        <KeepAlive cachekey="xx-input">
          <Input />
        <KeepAlive>
      </div>
    );
  }

  return (
    <div title="页面2">
      <KeepAlive cachekey="xx-input">
        <Input />
      <KeepAlive>
    </div>
  );
};

CJY0208 avatar Aug 11 '22 02:08 CJY0208