如何解决this.setState在react.js类中不起作用

145 阅读1分钟

当我在链接状态下使用this.setState函数时,我从React得到一个空字符串,但实际上,这应该返回一个URL。我没有弄明白,因为我在我所有的项目中都使用了同样的方法,但这并不奏效!!

export class LiveStream extends Component<Props, State> {
  myLink: string;
  constructor(props: Props) {
    super(props);

    this.state = {
      id: "",
      publicKey: "",
      link: "",
      live: true,
    };
  }

  async componentDidMount() {
    const last3 = window.location.href.slice(-42); // 👉️ Public Key
    console.log(last3);

    let streamKey: any[] = [];

    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const contract = new ethers.Contract(
      "<Contract-Key>",
      LiveStreamContract.abi,
      provider
    );

    const contractData = await contract.getLiveStream();

    for (let index = 0; index < contractData.length; index++) {
      const element = contractData[index];

      if (element.publicKey.toLowerCase() === last3.toLowerCase()) {
        streamKey.push(element);
      }
    }

    const url: string = `http://localhost:8000/live/${streamKey[0].id}.flv`;
    this.setState({ link: url });
  }
  render() {
    if (this.state.live === true) {
      return (
        <ReactFlvPlayer
          url={this.state.link}
          isMuted={false}
          isLive={true}
          showControls={false}
          enableStashBuffer={false}
        />
      );
    } else {
      return "offline";
    }
  }
}