使用react-dropzone实现CSV上传时报TypeError: children is not a function错误
问题原因
你使用的react-dropzone v10及以上版本采用Render Props设计模式,要求<Dropzone>组件的子元素必须是可执行的函数,用来接收拖拽状态、绑定DOM属性等参数。你直接传入了静态JSX <div>节点,源码执行children(...)调用时触发类型错误。
修复方案
1. 修正Dropzone组件用法
将你render方法里的Dropzone部分替换为如下代码:
<Dropzone accept=".csv" onDropAccepted={this.onDrop.bind(this)}> {({getRootProps, getInputProps}) => ( <div {...getRootProps()}> <input {...getInputProps()} /> <p>Drop some files here</p> </div> )} </Dropzone>
其中getRootProps用来给拖拽容器绑定所需的事件属性,getInputProps用来给隐藏的上传input绑定属性,是组件要求的标准写法。
2. 其他可选优化点
- 在组件constructor中初始化state,避免setState告警:
constructor(props) { super(props); this.state = { files: [] }; } - 修正fetch请求的返回解析逻辑,
fetch响应没有result属性,替换为r.json(),本地调试注意检查接口是http还是https避免SSL报错:fetch('http://localhost:8080/api/users', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(newUser) }).then(r => r.json()) - 可待CSV全量解析完成后批量提交用户数据,减少频繁发起POST请求的性能消耗。
内容的提问来源于stack exchange,提问作者nemoxi
相关产品推荐
相关产品推荐

