【问题标题】:React API object in JavaScript keeps saying undefinedJavaScript 中的 React API 对象一直说未定义
【发布时间】:2017-08-13 07:53:40
【问题描述】:

我正在使用 JSON 占位符对象将对象名称放置在每个列表项中。我不断得到“未定义”而不是 data.name。

感谢阅读!以下是我的代码供您查看:

console.clear()

class App extends React.Component {

searchFunction() {
fetch('http://jsonplaceholder.typicode.com/posts/1/comments', {
  method: 'GET'
}).then((res) => {
res.json().then((data) => {
  console.log(data);
  data.forEach(function() 
   {document.getElementById('datalog').innerHTML+=
    `<ul>
      <li>
        ${data.name}
      </li>
     </ul>`
  });
})
})
    .catch((err) => {
      console.log(err);
  })
}
  render() {
return (
  <div className='App'>
    <h1>Welcome to VCP!</h1>
    <div id="datalog"></div>
    {this.searchFunction()}
  </div>
    )
  }
}


ReactDOM.render(
  <App/>,
  document.getElementById('root')
)

【问题讨论】:

    标签: javascript json api reactjs


    【解决方案1】:

    你不能在 js 函数中使用 ${data.name} .. 它应该像 document.getElementById('datalog').innerHTML+= <ul> <li>'+data.name+' </li> </ul>

    【讨论】:

      【解决方案2】:

      您忘记将参数传递给您的 forEach 调用,如果应该是这样的:

      console.clear()
      
      class App extends React.Component {
      
        searchFunction() {
          fetch('http://jsonplaceholder.typicode.com/posts/1/comments', {
            method: 'GET'
          }).then((res) => {
          res.json().then((data) => {
            console.log(data);
            data.forEach(function(item){document.getElementById('datalog').innerHTML+=
              `<ul>
                <li>
                  ${item.name}
                </li>
               </ul>`
            });
          })
        })
              .catch((err) => {
                console.log(err);
            })
      }
        render() {
          return (
            <div className='App'>
              <h1>Welcome to VCP!</h1>
              <div id="datalog"></div>
              {this.searchFunction()}
            </div>
          )
        }
      }
      
      
      ReactDOM.render(
        <App/>,
        document.getElementById('root')
      )
      

      【讨论】:

        猜你喜欢
        • 2012-09-30
        • 1970-01-01
        • 2015-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-18
        • 2017-08-20
        相关资源
        最近更新 更多