我想 JSONify 一個 React 組件的狀態并將狀態轉儲到資料庫中。我的代碼目前如下所示:
const [exampleState, setExampleState] = useState([
{
componentName: "Test component",
component: <TestComponent props={testComponentData} />,
}.
{
componentName: "Another test component",
component: <AnotherTestComponent props={anotherTestComponentData} />
}
]);
是否可以按原樣將狀態 JSON 化,將其存盤在資料庫中,稍后從資料庫中檢索資料作為 JSON,然后將其轉換回有效狀態?
如果不是,那么將這種狀態轉換為可以存盤在資料庫中并再次將其從 JSON 物件轉換回狀態的 JSON 物件的推薦程序是什么?
uj5u.com熱心網友回復:
我不認為整個組件可以像這樣存盤到資料庫中。更合理的方法應該是將component nameand存盤props到 DB 并使其react component留在前端。
一個簡單的例子可能是這樣的。
D B
[
{
name: 'TestComponent',
props: testComponentData
},
{
name: 'AnotherTestComponent',
props: anotherTestComponentData
}
]
前端
import TestComponent from './TestComponent';
import AnotherTestComponent from './AnotherTestComponent';
const renderComponent = (name, props) => {
const mapNameToComponent = {
TestComponent: TestComponent,
AnotherTestComponent: AnotherTestComponent
}
const Component = mapNameToComponent[name];
if (!Component) return null;
return <Component {...props} />
}
const Page = () => {
const [name, setName] = useState();
const [props, setProps] = useState();
useEffect(() => {
// call api to getDB data
// The data structure of dbData just like the DB shows
const dbData = getDB();
// store the DB data in the state
const TestComponentData = dbData[0];
setName(TestComponentData.name);
setProps(TestComponentData.props);
}, [])
// choice which component you want to render by name and props
return renderComponent(name, props)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450801.html
上一篇:使用宣告檔案覆寫賽普拉斯打字稿
下一篇:關于會話cookie的安全問題
