标准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()后更新,但页面不使用更新的数据呈现。
警告:我用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()放在单独文件中的原因是由于几个不同的页面可能最终试图更新配置设置。
我有类似的问题…试图重现你在这里所做的一切,我相信你必须"订阅"。对于你想要更新渲染函数的键。
From github readme:
store.subscribe & globalState.subscribe
If you want to listen to changes in a store you can subscribe to it by using
store.subscribe. it accepts an observer function. For example
// Subscribe to store changes
const unsubscribe = store.subscribe(function(key: String, value: Any){
// key is the key for a global state that has changed
// value is the new value of a global state
})
// You can unsubscribe by calling the result
unsubscribe();
这是它是如何完成在测试文件:
import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { createStore } from '../src/';
const store = createStore();
store.setState("count", 0);
let testVal1 = 0;
let testVal2 = 0;
test('should update testVal1 & testVal2 through subscribers', () => {
const { result } = renderHook(() => store.useState("count"))
act(() => {
store.subscribe((key, value) => {
testVal1 = 1
})
store.getState("count").subscribe((value) => {
testVal2 = 2
})
result.current[2](count => 1)
})
expect(testVal1).toStrictEqual(1);
expect(testVal2).toStrictEqual(2);
})