设置组件状态,来自无法访问的变量

Set component state, from unreachable variable

我怎样才能 media.duration 生活在国家环境中?

现在我无法访问它,即使在尝试更改状态后也是如此

  handleClick(e) {
        e.preventDefault();

    var reader = new FileReader();
    reader.readAsDataURL(this.state.uploadedFile);
    reader.onload = function() {
      var media = new Audio(reader.result);
      media.onloadedmetadata = function() {
        console.log(media.duration); // <-- THIS WORKS!!!!!!!!!!!!!!
      };
    };
    console.log(media.duration) //<------THIS DOES NOT WORK!!!!!!!!!!
    console.log("The link was clicked.");
    console.log(this.state.duration);
}

来自:

_________________________________________

我试过了,但没用

    this.setState({duration:media.duration},()=>{
console.log(this.state.duration)
})

这是因为您使用的媒体变量超出了范围。 请试试这个。

handleClick(e) {
    e.preventDefault();
    var reader = new FileReader();
    reader.readAsDataURL(this.state.uploadedFile);
    reader.onload = () => {
      var media = new Audio(reader.result);
      media.onloadedmetadata = () => {
        console.log(media.duration); // <-- THIS WORKS!!!!!!!!!!!!!!
        this.setState({duration: media.duration});
      };
    };
}