简体   繁体   English

如何将类的递归函数转换为redux动作?

[英]How to convert a class's recursive function to be a redux action?

A recursive function shown bellow locates in a class. 下面显示的递归函数位于一个类中。 And, no state modification happens in the code section. 并且,在代码部分中不会发生状态修改。

//delete target node and its subtree
function deleteSubTree(cur,nodearray){
    if(the node is not a leave) {
         //go to leaves
         deleteSubTree(cur.child,nodearray);
    }
    else{
        delete cur;
        if(cur.parent has a child) deleteSubTree(cur.parent,nodearray)
        else return;
    }
}

But because now I need to refactor my code to fit the redux framework, I need to turn this into a action. 但是因为现在我需要重构代码以适合redux框架,所以我需要将其转变为一个动作。 I think it should be converted to be 我认为应该将其转换为

export function deleteSubTreeAction(node) {
    return (diespatch)=>{
         ....
        dispatch(deleteSubTreeAction(node.rChild));
         ...
    };
}

However, this looks quite weird. 但是,这看起来很奇怪。 Any suggestions? 有什么建议么?

Split it into two actions: 将其分为两个动作:

  1. DELETE_SUBTREE_START
  2. DELETE_SUBTREE_END

Dispatch them like this: 像这样调度他们:

// Helper function / side effect
function deleteSubTree(cur, nodearray, done){
    if(the node is not a leave) {
         //go to leaves
         deleteSubTree(cur.child, nodearray, done);
    }
    else {
        delete cur;
        if (cur.parent has a child) {
            deleteSubTree(cur.parent, nodearray, done)
        } else {
            return done();
        }
    }
}

// Action creator
export function deleteSubTreeAction(node) {
    return (dispatch) => {
        ...
        dispatch({ type: 'DELETE_SUBTREE_START' });
        deleteSubTree(
            node.rChild,
            ?, // not sure if you need the second argument here?
            () => dispatch({ type: 'DELETE_SUBTREE_END' })
        );
        ...
    };
}

This way the recursive function can signal when it's done() and can take as long as it needs. 这样,递归函数就可以在done()时发出信号,并且可以花费所需的时间。 For performance, consider limiting the maximum tree depth though, which could dispatch something like DELETE_SUBTREE_ABORT . 为了提高性能,请考虑限制最大树的深度,这可能会派发DELETE_SUBTREE_ABORT东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM