[英]Using setState without React Dev Tools
We have $r
available when React Dev Tool extension is installed.当安装了 React Dev Tool 扩展时,我们有$r
可用。 Is it possible to have something like that without using React Dev Tool?在不使用 React Dev Tool 的情况下有可能拥有这样的东西吗?
eg例如
With $r
this works:使用$r
这有效:
$r.setState((state) => {
return {username: "blabla"}
})
I need to do something like that but without the react dev tools.我需要做类似的事情,但没有反应开发工具。
Ok I was able to do it finally myself with help from Access third party React app state from outside React好的,我最终能够在来自React 外部的 Access 第三方 React 应用程序状态的帮助下自己完成
Modified code from that answer here to change the state as well:来自该答案的修改代码也更改了状态:
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
will be the id of the root element of react app eg #app
rootNode
将是 react app 根元素的 id,例如#app
globalAttributeName
will be the Key that you need to change globalAttributeName
将是您需要更改的 Key
newValue
will be the new state of that key newValue
将是该键的新状态
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.