javascript - 使用 Reactjs 未定义 componentDidMount 内的变量

标签 javascript json 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() {...}}

但是,我在 componentDidMount() 中得到以下行的 'url' is not Defined no-undef:fetch(url) >。如何在 componentDidMount 方法中调用 url 变量?

最佳答案

使用 this.props.url 访问传递给 UserNoti 类的 url 属性。

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

关于javascript - 使用 Reactjs 未定义 componentDidMount 内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53049951/

相关文章:

javascript - 错误消息 : DateField. getValue() 不是函数

javascript - 从asp.net webservice解析Json数据并将其填充到asp.net下拉列表中

java - 使用 REST API 和 HttpClient 时在 Java 中打印 JSON 响应

javascript - React native 听写在 iOS 上突然削减单词

python - 使用生成步骤打包 Web 应用程序的 pythonic 方法是什么?

javascript - 以循环顺序显示多个信息 JQuery - Flapper

JavaScript。引用文献问题。遗产。范围

javascript - jQuery 变量(在 html 中选择)

ios - 在 Swift 3 中更改来自 JSON url 的数据的行高

javascript - React 中的多个 url API