【问题标题】:Get state and update state in a non react component in nextjs在 nextjs 的非反应组件中获取状态和更新状态
【发布时间】:2021-09-19 21:59:23
【问题描述】:

我正在开发一个 nextjs 项目,其中我有一个与 pages 文件夹级别相同的 helpers 文件夹。

我在 helpers 文件夹中有一个 ts 文件,在这里我想根据最新状态获取最新状态和更新状态

这就是我获取状态的方式

store().getState()

store 从 store.js 导入的地方

我根据之前的状态更新状态

    const state = store().getState()

    if(!state.currentUser){   // here im checking if state has currentUser
        store().dispatch(Action)  // here im calling action which will update the state
    }

    do further operations

这里的问题是更新状态后我没有从store().getState() 获得更新的状态。我管理事情的方式是否正确?如何获取更新后的状态?

*EDIT* : Im sending a helper function as a prop to many if my page components. Now that i dont want to touch this , i somehow want to get the updated state and dispatch actions based on the state itself. Note that the hepler function is not a functional component

提前致谢

【问题讨论】:

    标签: javascript reactjs redux react-redux next.js


    【解决方案1】:

    问题是您使用的这个存储不是 React 的一部分,所以 React 不知道数据何时发生变化。你必须创建一种方法让 React 知道数据发生了变化,这样它就可以重新渲染你的组件或触发一个动作。 您的商店是否提供订阅更改的方式?如果是这样,你可以在你的组件中做这样的事情(假设你正在使用钩子):

    编辑:可重复使用的钩子方式:

    export const useStore = () => {
        const [storeState, setStoreState] = useState(store().getState());
        useEffect(() => {
          const subscribeFunc = (newState) => setStoreState(newState));
          store().subscribe(subscribeFunc);
          return () => {
            store().unsubscribe(subscribeFunc);
          }
        }, [])
    
        return [storeState, store().dispatch]
      }
    

    然后在你的组件中

    const [storeState, dispatch] = useStore();
    
    // listen to changes of the currentUser and fire actions accordingly
    useEffect(() => {
      if (!storeState.currentUser) {
        dispatch(Action)
      }
    }, [storeState.currentUser])
    

    初始方式:

    // sync the store state with React state
    const [storeState, setStoreState] = useState(store().getState());
    useEffect(() => {
      const subscribeFunc = (newState) => setStoreState(newState));
      store().subscribe(subscribeFunc);
      return () => {
        store().unsubscribe(subscribeFunc);
      }
    }, [])
    
    // listen to changes of the currentUser and fire actions accordingly
    useEffect(() => {
      if (!storeState.currentUser) {
        store().dispatch(Action)
      }
    }, [storeState.currentUser])
    

    通过在组件中设置更改时的状态,React 现在知道数据已更改并会采取相应的行动。

    这是一种非常本地化的方法来解释这个概念,但显然最好创建一个可重用的钩子,以便在您的应用中用于任何商店。

    【讨论】:

    • 非常感谢您的努力。我会试试这个你能创建一个可重用的钩子,我可以在其中获取更新的状态并可以在其中调度操作吗?
    • @VijayThomas 当然,我更新了我的答案。它基本上是相同的代码,但它被移动到一个钩子中,您也可以在其他组件中使用。
    • 我不能像你一样使用钩子。它抛出一个错误Can be used only inside functional components@yts
    • 我将一个辅助函数作为道具传递给我的页面组件。在这个辅助函数中,我想根据条件获取更新的状态和调度操作。如果您需要更多数据,请随意
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2016-01-19
    • 1970-01-01
    • 2018-11-03
    • 2021-10-22
    • 2020-04-11
    • 2015-05-21
    相关资源
    最近更新 更多