這里是 ReactTS 的新手。有人可以向我解釋為什么變數content是undefined以及如何設定它以便我可以將它的值傳遞給<App />?
index.tsx它在檔案和后續檔案中都顯示未定義App.tsx。
索引.tsx
import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// Declare type for drupalSettings.
declare global {
interface Window {
drupalSettings: {
mydashboard: Settings;
};
}
}
// Declare types for the React component.
interface Elements {
content: string[];
}
interface Settings {
[index: string]: Elements;
}
// Get Drupal settings.
console.log('window.drupalSettings', window.drupalSettings.mydashboard) <!--- shows correct value --->
const drupalAndReactApp: Settings = window.drupalSettings.mydashboard || '';
console.log('drupalAndReactApp', drupalAndReactApp, drupalAndReactApp['test']);<!--- shows correct value --->
const { content } = drupalAndReactApp['test'];
console.log('content', content) <!--- shows undefined --->
ReactDOM.render(<App content={content} />, document.getElementById('my-app-target'));
索引.tsx
let accessToken = "";
let embedUrl = "";
let reportContainer: HTMLElement;
let reportRef: React.Ref<HTMLDivElement>;
let loading: JSX.Element;
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface AppProps { content: string[] };
interface AppState { accessToken: string; embedUrl: string; error: string[]};
class App extends React.Component<AppProps, AppState> {
constructor(props: AppProps) {
super(props);
const { content } = props;
this.state = { accessToken: "", embedUrl: "", error: [] };
reportRef = React.createRef();
console.log('props', props, content) <!--- shows undefined --->
// Report container
loading = (<>
<div id="welcome">
Welcome
</div>
<div
id="reportContainer"
ref={reportRef} >
Loading the report...
</div>
</>
);
}
...
編輯
控制臺日志的輸出...
window.drupalSettings Object { test: "[\"authenticated\",\"administrator\"]" }
drupalAndReactApp Object { test: "[\"authenticated\",\"administrator\"]" } ["authenticated","administrator"]
content undefined
props Object { content: undefined } undefined
編輯 2
window.drupalSettings Object { content: "[\"authenticated\",\"administrator\"]" }
drupalAndReactApp Object { content: "[\"authenticated\",\"administrator\"]" } ["authenticated","administrator"]
content undefined
props Object { content: undefined } undefined
uj5u.com熱心網友回復:
根據您的資料,您的 TypeScript 定義應如下所示:
interface Settings {
[index: string]: string;
}
稍后決議 JSON:
const content: string[] = JSON.parse(drupalAndReactApp.content);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432987.html
上一篇:如何在我的Appery.ioIonic5應用程式中呼叫API?
下一篇:提交資料時渲染一個框
