Closed alvinhui closed 4 years ago
原始需求来自于 @亦森 :
https://codesandbox.io/s/gallant-fast-w8klw 第三十八行代码期望获取到最新的 state。
在开发中会有这类需求。例如:
import { useState, useMemo } from "React"; import { getModelState } from "./store"; function Logger({ foo }) { // case 1 在闭包中获取最新状态(能力欠缺,期望有 getModelState 这样的 API) const doOhterThing = useCallback( (payload) => { const counter = getModelState('counter'); alert(counter + foo); }, [foo] ); // case 2 只使用状态而不订阅更新(性能优化,期望有 getModelState 这样的 API) function doSomeThing() { const counter = getModelState('counter'); alert(counter); }; return ( <div> <button onClick={doSomeThing}>click 1<button> <button onClick={doOhterThing}>click 2<button> </div> ); }
参考 redux ,提供 getState API:
import { useState, useMemo } from "React"; import store from "./store"; function Logger({ foo }) { // case 1 在闭包中获取最新状态(能力) const doOhterThing = useCallback( (payload) => { const counter = store.getState().counter; alert(counter + foo); }, [foo] ); // case 2 只使用状态而不订阅更新(性能优化的手段) function doSomeThing() { const counter = store.getState().counter; alert(counter); }; return ( <div> <button onClick={doSomeThing}>click 1<button> <button onClick={doOhterThing}>click 2<button> </div> ); }
需求
原始需求来自于 @亦森 :
https://codesandbox.io/s/gallant-fast-w8klw 第三十八行代码期望获取到最新的 state。
在开发中会有这类需求。例如:
方案
参考 redux ,提供 getState API: