我正在尝试设置我的FileList组件的状态,但我一直收到错误
Unhandled Rejection(TypeError):无法从第43行读取未定义的属性'setState' - this.setState({list:entries});
我已将功能绑定到此,正如在线建议的那样,是否有人知道如何使其工作
export default class FileList extends Component {
constructor(props) {
super(props);
this.getList = this.getList.bind(this);
this.renderFiles = this.renderFiles.bind(this);
this.state = {
zipFile: props.zipFile,
uploadPressed: props.uploadPressed,
list: []
}
}
getList() {
var entries = new Array;
let zip = new JSZip();
JSZip.loadAsync(this.state.zipFile).then(function (zip) {
zip.forEach(function (zipEntry) {
if(zipEntry.split('/')[1] === "color"){
if(zipEntry.endsWith('.png')) {
entries.push(zipEntry.split('/').pop());
} else if (zipEntry.endsWith('/')) {
} else {
}
} else if(zipEntry.split('/')[1] === "mono") {
if(zipEntry.endsWith('.png')) {
entries.push(zipEntry.split('/').pop());
} else if (zipEntry.endsWith('/')) {
} else {
}
} else if(zipEntry.endsWith('.sslt')) {
} else {
}
});
alert(entries[0]);
this.setState({list: entries});
});
}
render() {
return <div className="file-list">
<div className="list-zip" >
<div className="list-zip-name">
{this.state.zipFile.name}
</div>
<div className="list-zip-size">
{this.state.zipFile.size} Bytes
</div>
<div className="list-zip-x" >
<button className="x-button" onClick={close}>X</button>
</div>
</div>
<hr className="hr"/>
{this.renderFiles()}
</div>
}
renderFiles() {
if(this.state.uploadPressed === true) {
this.getList();
return <File fileName={this.state.list[0]} />
}
}
}
3 回答
使用箭头函数更改回调函数:
你的主函数有一个
.bind
但在这个函数中你正在使用.then
和forEach
方法的常规回调函数 . 这些功能创建了自己的范围,你正在失去this
. 使用箭头功能,您不会松开this
'范围 .额外信息:您也可以为getList函数使用箭头函数 . 通过这种方式,您不需要在构造函数中绑定它 .
事实上,您应该使用箭头函数来避免丢失当前上下文,因为其他用户已经报告过,您有另一个错误,一旦您修复了上一个错误就会引发错误 .
你在
render
方法中调用了setState
,这将创建一个无限循环,以避免它只是将getList
方法放在componentDidMount
钩子里面这是一个范围问题 . 你的回调函数没有't have access to the component' s
this
. 您需要使用.bind(this)
或箭头操作符(() => {}
)来访问函数中的this