我有一个react-redux应用程序,其中一个触发的操作需要检查商店中是否存在一些数据。如果数据不存在,我想放弃操作,不想继续,但是如果数据存在,我们想要触发另一个更新存储的操作。我想知道怎样做才是正确的方法?下面的代码片段/伪代码模仿了类似的东西。
<MyComponent onClick={onClickHandler}/>
onClickHandler = () => {
if(checkIfDatapresentInStore) {
// anActionHandler();
} else {
anotherActionHandler();
}
}//Redux-store
store = {
dataPresentInStore: true
}谢谢
发布于 2020-10-19 12:42:42
您可以使用getState存储方法。它将返回存储中存在的当前状态。然后,您只需检查您正在查找的状态,并基于此触发操作。
发布于 2020-10-19 12:55:47
为了详细说明Sunny的回答,这是可以在操作创建器或组件的处理函数中完成的事情。如果你想让dataPresent状态对你的组件可用,这真的取决于你。
通过actions.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.中的示例
https://stackoverflow.com/questions/64421137
复制相似问题