class Uploader extends React.Component {
constructor(props) {
super(props);
this.state = {
data: '',
name:'',
loading: false
}
}
}
这是我在this.state.load中加载值的函数
onChange(e) {
let files = e.target.files;
let reader = new FileReader();
reader.readAsDataURL(files[0]);
this.state.name = files[0].name;
reader.onload = ((e) => {
console.log("file is",e.target.result);
const formData = {data: e.target.result};
this.state.data = formData;
this.setState({data: this.state.data});
console.log(this.state.data); // here it gives value whats inside file
});
this.setState({'name': this.state.name});
console.log(this.state.data) // here it doesn't print anything
}
在任何函数中调用它:
onUpload() {
console.log(this.state.data);
}
它不呈现。它给出:“错误状态未定义”。 我如何在其他函数或其他代码范围中使用this.state.data,以其他任何方式调用此值或需要此更正????
答案 0 :(得分:2)
制作一个函数(箭头函数除外)将创建它自己的this
实例。
因此,函数内部没有状态对象。要解决此问题,您有两种方法-
使用箭头功能-
使用箭头功能不会创建它自己的this
onUpload = () => {
console.log(this.state.data)
}
将函数的this
绑定到类的this
constructor (props) {
super(props)
this.onChange = this.onChange.bind(this);
this.onUpload = this.onUpload.bind(this);
}
希望这对您有所帮助。 :)
答案 1 :(得分:1)
在构造函数中使用绑定:
constructor (props) {
super(props)
this.onChange = this.onChange.bind(this);
}
或使用箭头功能:
onChange = (e) => {
...
}
答案 2 :(得分:1)
将您的方法与该类绑定,否则this
将是undefined
class Uploader extends React.Component {
constructor(props) {
super(props);
this.state = {
data: '',
name :'',
loading : false
}
this.onChange = this.onChange.bind(this);
}
}
或在类属性中使用箭头功能(如果有支持的话)。
class Uploader extends React.Component {
constructor(props) {
super(props);
this.state = {
data: '',
name :'',
loading : false
}
}
onChange = () => {}
}
答案 3 :(得分:0)
将您的功能更改为此:
onChange(e){
const that = this ; // add this
let files = e.target.files;
let reader =new FileReader();
reader.readAsDataURL(files[0]);
// don't set directly value to state !
// this.state.name = files[0].name;
this.setState({name: files[0].name}, function() {
console.log(that.state.name) // here it doesn't print anything
});
reader.onload = ((e) => {
console.log("file is",e.target.result);
//const formData = { data : e.target.result }
//this.state.data = formData;
// Use setState callback to get state result
that.setState({data : e.target.result}, function() {
console.log(that.state.data) // here it gives value whats inside file
});
});
}