【发布时间】:2020-10-27 22:51:24
【问题描述】:
我正在尝试使用共享祖先在文件上传器和表之间中继数据。我有一个文件上传器,但是一旦我添加了我的 JSON 文件,我就会收到错误 TypeError: setProductState is not a function。
当我控制台记录我的 inputJson 文件时,它会运行,但是当我应用 setProductState 并输入我的文件时,我会收到此错误。
根据我阅读的内容,我不需要绑定,因为我使用的是箭头语法,但我可能需要一个“this”。
欢迎任何想法或批评。
function FileUploader({ productState, setProductState }) {
const onDrop = useCallback((acceptedFiles) => {
// this.setProductState = this.setProductState.bind(this); tried
acceptedFiles.forEach((file) => {
const reader = new FileReader()
reader.onload = () => {
const inputJson =
this.inputJson = inputJson //tried
JSON.parse(reader.result)
setProductState(inputJson); //console.log goes through
}
reader.readAsText(file)
})
}, [])
const {getRootProps, getInputProps} = useDropzone({onDrop})
return (
<div {...getRootProps({style})}>
<input {...getInputProps()} value={productState}/>
<p>Drag files here, or click to browse</p>
</div>
)
}
Ancestor.js
import React, { useState } from 'react'
import FileUploader from './FileUploader'
import Table from './Table'
const Ancestor = () => {
const [products, setProducts] = useState({});
return <>
<FileUploader productState={products} setProductState={setProducts} />
<Table productState={products} />
</>;
}
export default Ancestor;
【问题讨论】:
-
您可以从检查
setProductState到底是什么开始。如果它不是一个函数或者它的 undefined,检查你是否正确传递了 props。 -
显示父组件的代码。 SetProductState 是在哪里定义的?
-
@Benjamin 我已经添加了父组件。它在祖先中定义。谢谢两位的建议。