簡體   English   中英

在沒有 React Dev Tools 的情況下使用 setState

[英]Using setState without React Dev Tools

當安裝了 React Dev Tool 擴展時,我們有$r可用。 在不使用 React Dev Tool 的情況下有可能擁有這樣的東西嗎?

例如

使用$r這有效:

$r.setState((state) => {
    return {username: "blabla"}
})

我需要做類似的事情,但沒有反應開發工具。

好的,我最終能夠在來自React 外部的 Access 第三方 React 應用程序狀態的幫助下自己完成

來自該答案的修改代碼也更改了狀態:


function setAppState(rootNode, globalAttributeName, newValue) {
    var $root = $(rootNode)._reactRootContainer;
    var reactState = false;
    var searchStack = [];
    var searched = [];

    // Fetch the "_internalRoot" attribute from the DOM node.
    for ( const key in $root ) {
        if (0 === key.indexOf('_internalRoot') ) {
            searchStack.push($root[key]);
            break;
        }
    }

    // Find the state by examining the object structure.
    while (searchStack.length) {
        var obj = searchStack.pop();

        if (obj && typeof obj == 'object' && -1 === searched.indexOf(obj)) {
            if ( undefined !== obj[ globalAttributeName ] ) {
                reactState = obj;
                break;
            }

            for (i in obj) {
                searchStack.push(obj[i]);
            }
            searched.push(obj);
        }
    }

    // Take the last pushed object as it contains the State to be changed
    state = searched[searched.length - 1].memoizedState;
    state[globalAttributeName] = newValue;

    return state;

}

rootNode將是 react app 根元素的 id,例如#app

globalAttributeName將是您需要更改的 Key

newValue將是該鍵的新狀態

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM