簡體   English   中英

使用Reactjs未定義componentDidMount內部的變量

[英]Variable inside componentDidMount are undefined using Reactjs

我有以下代碼塊:

const UserNotification = ({ user }) => {
  const url = `https://api.thingspeak.com/channels/${user.channel}/feeds.json?&dynamic=true`;
  console.log(url); //https://api.thingspeak.com/channels/594944/feeds.json?&dynamic=true OK
  return <UserNoti url = { url } />
}

class UserNoti extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: [],
      isLoaded: false,
    };
  }

  componentDidMount() {
   fetch(url)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json,
        });
      });
  }
 render() {...}}

但是,我得到的'url' is not defined no-undef為以下行'url' is not defined no-undefcomponentDidMount() fetch(url) componentDidMount() 如何在componentDidMount方法內調用url變量?

使用this.props.url訪問傳遞給UserNoti類的url屬性。

componentDidMount() {
   fetch(this.props.url)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json,
       });
   });
}

UserNotification您將url作為組件UserNotification傳遞。 使用ES6類組件,可以使用this.props.propName訪問道具。 因此,在您的情況下,您應該執行以下操作:

componentDidMount() {
  fetch(this.props.url)
    .then(res => res.json())
    .then(json => {
      this.setState({
        isLoaded: true,
        items: json,
      });
    });
}

有關組件和道具的官方React文檔的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM