【问题标题】:Is there a way to cache data coming from redux connect in React function component with using useRef()?有没有办法使用 useRef() 在 React 函数组件中缓存来自 redux 连接的数据?
【发布时间】:2019-12-30 18:47:28
【问题描述】:

我在 Class 组件中缓存数据的方式如下: 1.在componentDidMount中进行异步API调用 2.通过redux获取API响应和dispatch数据 3. 通过将 state 映射到 prop 来使用响应数据

我想要做的是在您获得带有映射的 redux 状态值的 API 响应后立即缓存数据 函数组件中useEffect 的内部 ( 它适用于类组件。但我想知道我应该如何让它在函数组件中工作)

export class MyClassComponent extends React.Component {
    private readonly _myCachedData = {
         'data1': {}
    }

    public async componentDidMount() {
        await this.loadAsyncData();
    }

    private loadAsyncData() {
        const { makeAPICall } = this.props
        await makeAPICall();
        return this._myCachedData.data1 = this.props.data1FromReduxConnect;
    }
}

export const mapStateTopProps = (state) => {
    const { data1FromReduxConnect } = state;
    return data1FromReduxConnect;
}
...

我尝试过的:

export const MyFunctionComponent = props => {
    const { data1FromReduxConnect } = props;
    const myCachedData = React.useRef();
    const loadAsyncData = () => {
        const { makeAPICall } = this.props
        await makeAPICall();
        return myCachedData.current = data1FromReduxConnect;
    }
    React.useEffect(()=> {
        await loadAsyncData();
    })

}

export const mapStateTopProps = (state) => {
    const { data1FromReduxConnect } = state;
    return data1FromReduxConnect;
}

我只能获取data1FromReduxConnect 的先前值,不像类组件在 API 调用后得到更新的值this.props.data1FromReduxConnect

不确定我是否应该为它保留类组件,或者有没有办法处理这个问题! 谢谢!!

【问题讨论】:

  • 如果数据已经在存储中,为什么还需要缓存?

标签: reactjs react-redux


【解决方案1】:

我认为这不是使用useRef 钩子的正确方法。类似于 React 的类组件的createRef(),实际上是用来访问函数式组件中的 DOM。

如果 HTTP 请求在 MyFunctionComponent 初始化时只发生一次,我们可以使用 [] 作为 useEffect 钩子中的第二个参数,这将导致此效果为 run only once。此外,我们将需要使用useState 挂钩来跟踪组件的状态,该状态将使用 redux 存储中的值进行更新。

export const MyFunctionComponent = props => {
    const { data1FromReduxConnect } = props;
    const [ myData, setMyData ] = useState();

    const loadAsyncData = async() => {
        const { makeAPICall } = this.props
        await makeAPICall();
    }

    useEffect(()=> {
      async function getData() {
        await loadAsyncData();
      }
      getData();
      // do the rest to get and store data from redux
      setMyData(data1FromReduxConnect);
    }, [])

}

【讨论】:

  • 嗨!谢谢你的回答。但是 react doc 告诉我们,它可以在函数组件中使用,就像在类中使用实例字段一样。 reactjs.org/docs/hooks-reference.html#useref
  • @tlrmacl 是的,同意,但在这种情况下,您并没有完全尝试访问 DOM 实例,对吧?
猜你喜欢
  • 1970-01-01
  • 2020-06-22
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 2017-04-13
  • 2021-07-30
  • 1970-01-01
相关资源
最近更新 更多