【发布时间】:2021-10-06 00:08:29
【问题描述】:
标准JS文件:
// functions.js
import cockpit from "cockpit";
import { store } from "state-pool";
const global_status = {
key1: null,
key2: null,
}
store.setState("status", global_status);
function update_config(data, message) {
const json_data = JSON.parse(data);
store.setState("status", {
key1: json_data.key1,
key2: json_data.key2,
};)
}
export function get_config() {
cockpit.spawn(python_script, superuser: "try", err: "message" })
.done(function (data, message) { update_config(data, message) })
.fail(function (error) { console.log(["spawn() failed: ", error]) });
}
// Initial loading of values
get_config()
在我的 JSX 文件中,我有这个:
// app.jsx
import React, { useEffect } from 'react';
import { Alert, Card, CardTitle, CardBody } from '@patternfly/react-core';
import { store, useGlobalState } from 'state-pool';
function ShowStatus () {
const stat = store.getState("status");
const info = stat.key1 ? "info" : !stat.key1 ? stat.installed ? "error" : "warning";
const status = stat.key2 ? "Enabled" : !stat.key2 ? "Available" : "Unkown";
return (
<Alert variant={info} title={status} />
);
}
export function App () {
const [status] = useGlobalState('status');
useEffect(
() => ShowStatus, [status]
);
return (
<Card>
<CardTitle>Status</CardTitle>
<CardBody>
<ShowStatus />
</CardBody>
</Card>
);
}
在 Fedora Cockpit 中渲染它时,它可以工作,但只有初始加载值(key1:null,key2:null)显示。调用 get_config() 后,状态页永远不会更新。
我使用了 console.log() 并验证了在调用 get_config() 后“状态”得到了更新,但页面没有使用更新的数据呈现。
CAVEAT:我已经有一段时间没有用 JS 编写代码了,这是我第一次使用 React。
我已经阅读了 React 文档以及来自 stackoverflow 的大约 30 个关于此问题的答案,但我仍然在绕过一些 Reactisms 时遇到了一些问题。
任何帮助将不胜感激。
更新:
我尝试过的一种变体:
// app.jsx
function ShowStatus (stat) {
const info = stat.key1 ? "info" : !stat.key1 ? stat.installed ?
...
}
export function App () {
...
<CardBody>
<ShowStatus stat={status} />
</CardBody>
...
将 get_config() 放在一个单独的文件中的原因是由于几个不同的页面最终可能会尝试更新配置设置。
【问题讨论】:
-
我尝试过的一种变体:
-
我现在唯一能想到的其他方法是让 python 脚本将更新保存到文件中,然后使用 cockpit.file().watch() 函数查看状态何时改变了。 python脚本返回一个json流,我已经设置了保存到文件以及返回一个json流。
标签: javascript reactjs global-variables render