在没有React开发工具的情况下使用setState



安装React Dev Tool扩展时,我们有可用的$r。在不使用React开发工具的情况下,有可能拥有这样的东西吗?

例如

有了$r,这就起作用了:

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

我需要做一些类似的事情,但没有react开发工具。

好的,在React 外部访问第三方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应用程序的根元素的id,例如#app

globalAttributeName将是您需要更改的密钥

newValue将是该密钥的新状态

相关内容

最新更新