【发布时间】:2020-02-21 14:08:56
【问题描述】:
这是codesandbox for the problem。
示例分为三个部分:
- 反应功能组件。
- Vanilla JS grid library。
- 使用Effect 将它们结合起来。
一个 useEffect 实例化网格,而另一个监听状态变化以更新网格。
在row is clicked in the grid library 之前一切正常。
我收到此错误。
TypeError: Cannot read property 'companyName' of undefined
471 | id={"input-companyName"}
472 | list={"options-companyName"}
473 | className={"form-input"}
> 474 | value={formJournalItems.companyName}
475 | onChange={handleDatalistChange}
476 | onKeyUp={handleKeyUp}
477 | ref={refCompanyName}
325 |
326 | function handleTableRowClick(journalItemId) {
327 | let journalItem = journalItems.filter(item => item.id === journalItemId)[0]
> 328 | setFormJournalItems(journalItem)
329 | }
330 |
331 | function isValidFormInputs() {
这里是有问题的代码,其余的可以在codesandbox看到。
let refCompanyName = React.createRef();
let refTable = useRef(null);
let table = useRef(null);
const [journalItems, setJournalItems] = useState([]);
const initialFormJournalItems = {
id: "",
journalId: "",
companyId: "",
companyName: "",
documentKey: "",
documentDate: "",
debitAccountId: "",
debitAccount: "",
debit: "",
creditAccountId: "",
creditAccount: "",
credit: ""
}
const [formJournalItems, setFormJournalItems] = useState(initialFormJournalItems);
useEffect(() => {
fetch(`http://localhost:4000/journals/${props.match.params.key}/items`)
.then(res => res.json())
.then(data => {
setJournalItems(data)
})
.catch(err => err);
table.current = new Tabulator(refTable.current, {
data: journalItems,
height: "100%",
layout: "fitColumns",
rowClick: function (e, row) {
//e - the click event object
//row - row component
console.log("tabulator journalitems", journalItems) // <------ EMPTY []
console.log(row._row.data)
handleTableRowClick(row._row.data.id)
},
columns: [
{ title: "Компанија", field: "companyName" },
{ title: "Документ", field: "documentKey" },
{ title: "Датум", field: "documentDate" },
{ title: "Должи", field: "debitAccount" },
{ title: "Износ", field: "debit" },
{ title: "Побарува", field: "creditAccount" },
{ title: "Износ", field: "credit" },
],
});
}, []);
// Updates the tabulator table on item change
useEffect(() => {
console.log("useEffect journalItems", journalItems) // <------ POPULATED
console.log("useEffect refTable", refTable)
console.log("useEffect table", table)
table.current.replaceData(journalItems)
}, [journalItems]);
function handleTableRowClick(journalItemId) {
let journalItem = journalItems.filter(item => item.id === journalItemId)[0]
setFormJournalItems(journalItem)
}
return (
<div>
<input
type={"text"}
name={"companyName"}
id={"input-companyName"}
list={"options-companyName"}
className={"form-input"}
value={formJournalItems.companyName}
onChange={handleDatalistChange}
onKeyUp={handleKeyUp}
ref={refCompanyName}
multiple
/>
</div>
)
【问题讨论】:
-
看起来您的
setFormJournalItems正在等待一个数组。您正在传递一个项目journalItem。也许您应该删除过滤器上的[0](第 327 行)
标签: javascript reactjs tabulator