繁体   English   中英

无法在其他函数中访问 this.state

[英]Can't access this.state in other function

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,以任何其他方式调用此值或需要此更正????

创建一个函数(箭头函数除外)会创建它自己的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);
}

希望这对你有帮助。 :)

在构造函数中使用绑定:

constructor (props) {
  super(props)
  this.onChange = this.onChange.bind(this);
}

或者使用箭头函数:

onChange = (e) => {
  ...
}

将您的方法与类绑定,否则this将是undefined

    1.
class Uploader extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
          data: '',
          name :'',
          loading : false
        }

        this.onChange = this.onChange.bind(this);
    }
}

或者,如果您支持它,则在类属性中使用箭头函数。

  1.  class Uploader extends React.Component { constructor(props) { super(props); this.state = { data: '', name :'', loading : false } } onChange = () => {} }

将您的功能更改为:

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
        });

    });


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM