На странице у меня есть элемент, встроенный в HTML:
{dataTable}
Который инициализируется как:
const [dataTable, setDataTable] = useState(<p>Data Table Loading...</p>);
И обновлено в функции useEffect, где я вызываю базу данных (супабазу PostgreSQL), чтобы получить данные для элементов списка дел.
let dataTable = <DataTable todos = {todos} todoLogs = {todoLogs} deleteTodo = {deleteTodo} toggleTodo = {toggleTodo}></DataTable>
setDataTable(dataTable)
Но когда он встроен в страницу, ничего не отображается и ошибок не возникает.
Другие элементы с простой структурой, например </h1>Hello World</h1>, отображаются на странице, а при использовании useState() и т. д., точно так же, как dataTable
Когда я console.info() элемент dataTable, я получаю:
Вывод console.info(dataTable) консоли браузера
Object
$$typeof
:
Symbol(react.element)
key
:
null
props
:
{todos: null, todoLogs: null, deleteTodo: ƒ, toggleTodo: ƒ}
ref
:
null
type
:
class DataTable
_owner
:
null
_store
:
{validated: true}
_self
:
undefined
_source
:
{fileName: 'C:/Users/user123/Desktop/coding-projects/2 }} testin…}/{{REACT}}/table-todo-testing/src/pages/Home.jsx', lineNumber: 132, columnNumber: 21}
[[Prototype]]
:
Object
Если вам интересно, вот как выглядит класс компонента DataTable:
class DataTable extends React.Component {
constructor(props) {
super(props);
this.todos = props.todos
this.todoLogs = props.todoLogs
this.deleteTodo = props.deleteTodo
}
render() {
const data = this.todoLogs;
// Map over the data to generate table rows
try {
const tableRows = data.map((todoLog) => (
<tr key = {todoLog.id}>
<td>{this.todos.find(x => x.id === todoLog.id).title}</td>
<td><input type = "checkbox" onChange = {() => {this.todos.find(x => x.id === todoLog.id)}} checked = {todoLog.d09_04_24}></input></td>
<td><input type = "checkbox" onChange = {() => {this.todos.find(x => x.id === todoLog.id)}} checked = {todoLog.d08_04_24}></input></td>
<td><input type = "checkbox" onChange = {() => {this.todos.find(x => x.id === todoLog.id)}} checked = {todoLog.d07_04_24}></input></td>
<td><input type = "checkbox" onChange = {() => {this.todos.find(x => x.id === todoLog.id)}} checked = {todoLog.d06_04_24}></input></td>
<td><input type = "checkbox" onChange = {() => {this.todos.find(x => x.id === todoLog.id)}} checked = {todoLog.d05_04_24}></input></td>
<td><input type = "checkbox" onChange = {() => {this.todos.find(x => x.id === todoLog.id)}} checked = {todoLog.d04_04_24}></input></td>
<td><input type = "checkbox" onChange = {() => {this.todos.find(x => x.id === todoLog.id)}} checked = {todoLog.d03_04_24}></input></td>
<td><input type = "checkbox" onChange = {() => {this.todos.find(x => x.id === todoLog.id)}} checked = {todoLog.d02_04_24}></input></td>
<td><button><i className = "material-icons" onClick = {() => {this.deleteTodo(todoLog.id)}}>delete</i></button></td>
</tr>
));
return (
<table>
<thead>
<tr>
<th>Title</th>
<th>09/04</th>
<th>08/04</th>
<th>07/04</th>
<th>06/04</th>
<th>05/04</th>
<th>04/04</th>
<th>03/04</th>
<th>02/04</th>
</tr>
</thead>
<tbody>
{tableRows}
</tbody>
</table>
);
} catch (error) {
console.info("22 could not render table, data not available", error)
}
// Render the table with the generated rows
}
}
Спасибо
Я пробовал:
Исследование проблемы
Экспериментируем с встраиванием других элементов HTML и получаем результаты.
Обеспечение отсутствия ошибок в других частях кода.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Похоже, ваш компонент DataTable недействителен.
Попробуйте удалить блок try/catch в компоненте рендеринга, чтобы убедиться, что вы что-то возвращаете (чего нет в блоке catch).
class DataTable extends React.Component {
render() {
return <p>Table</p>
}
}
Можете ли вы обновить свой вопрос с помощью вызова БД?
Кроме того, можете ли вы зарегистрировать props.todos в своем компоненте таблицы данных?
Я выделил проблему отображения в отдельный пост здесь: stackoverflow.com/questions/78399252/… Если вы будете довольны, я отмечу это как правильное решение? @devpolo
спасибо, кажется, таблица отображается - все еще не удается заставить таблицу динамически обновляться при обновлении базы данных... Интересно, связано ли это как-то с тем, как она встроена в html...