首页 > 解决方案 > ES6 类为自身调用 SetState 函数

问题描述

我正在构建一个 React 应用程序并尝试查看是否可以执行以下操作。有很多嵌套组件,并且正在更新的组件始终是最顶层的父组件。

这个想法是通过 ES6 类原型化的嵌套对象来构建它,如下所示:

class _Board {
    constructor(setStateFunction){
        this.items = [];
        this.setState = setStateFunction;
    }

    addSwimlane() {
        console.log(this);
        this.items = [...this.items, new _Swimlane()];
        this.setState(this);
    }
}

class _Swimlane {
    constructor(){
        this.id = uuidv4();
        this.items = [];
    }

    addColumn() {
        this.items = [...this.items, new _Column(this.id)];
        //Can we call the parent function through super to update the render?
    }
}

然后我有我的组件,我将在其中调用该函数:

const Main = (props) => {
    const [board, setBoard] = useState(new _Board());
    
    useEffect(() => { //Initial Render load setState
        setBoard(new _Board(setBoard));
    }, []);

    return (
        <div className="App" >
            {JSON.stringify(board)}
            <button onClick={() => board.addSwimlane()} >Add Swimlane</button>
        </div>
    );
};

我有两个问题:

  1. 你如何在一个类中传递这样的函数?我可以像往常一样通过箭头函数传递它们,但是当作为参数传递时,渲染不会更新。
  2. 一旦孩子嵌套,你如何调用父类?我应该通过我已经拥有的“addX”函数传递该函数并将其作为参考吗?

标签: javascriptreactjsecmascript-6es6-class

解决方案


推荐阅读