代码之家  ›  专栏  ›  技术社区  ›  me_digvijay

在执行操作之前检查redux存储中是否存在某些数据的最佳方法

  •  0
  • me_digvijay  · 技术社区  · 4 年前

    我有一个react redux应用程序,其中一个触发的操作需要检查商店中是否存在某些数据。如果数据不存在,我想放弃操作,不想继续,但是如果数据存在,我们想触发另一个更新存储的操作。 我想知道怎样做才是正确的方法?下面的代码片段/伪代码模拟了类似的情况。

    <MyComponent onClick={onClickHandler}/>
    
    onClickHandler = () => {
      if(checkIfDatapresentInStore) {
       // anActionHandler();
      } else {
        anotherActionHandler();
      }
    }
    

    //Redux商店

    store = {
        dataPresentInStore: true
    }
    

    谢谢

    0 回复  |  直到 4 年前
        1
  •  0
  •   sunny prakash    4 年前

    getState 存储方法。它将返回存储中的当前状态。然后,您只需要检查您正在寻找的状态,并在此基础上触发操作。

        2
  •  0
  •   tobiasfried    4 年前

    为了详细说明Sunny的答案,这是可以在action creator或组件的handler函数中执行的操作。如果你想成功的话,这真的取决于你 dataPresent 说明组件是否可用。

    通过中的action creator 动作.js

    // Note: the second argument to action callback is 
    // a function that returns the whole store
    const conditionalAction = () => (dispatch, getState) => {
      // Retrieve the whole store object and check what you need from it
      const { dataPresent } = getState();
    
      // Conditionally dispatch an action
      if (dataPresent) {
        dispatch({ type: "MAIN_ACTION" });
      } else {
        dispatch({ type: "OTHER_ACTION" });
      }
    }
    

    或者通过你的例子 MyComponent.js文件