【问题标题】:Reactjs - App.js:34 Uncaught TypeError: ch.map is not a functionReactjs - App.js:34 Uncaught TypeError: ch.map is not a function
【发布时间】:2022-01-24 20:57:43
【问题描述】:

当我从 Rest API 执行简单的 GET 请求时,我的 application.js 文件中出现 ch.map 不是函数错误:

function App() {

  const [ch, setCh] = useState([]);

   useEffect(()=>{

    fetch("https://localhost:12354/api/v1/Objects", {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic YWRt'
      }
    })
    .then( resp => resp.json())
    .then( resp => setCh(resp))
    .catch( error => console.log(error))


  }, [])

  return (
    <div className="App">
      <header className="App-header">
        <h1>Object Manager</h1>
      </header>
      <div className = 'layout'>
        <div> 
          { ch.map( i => {
            return <h2>{i.Name}</h2>
          })} 
          </div>
        <div> Object Details </div>
      </div> 
    </div>
  );
}

这是来自邮递员的相同 API 调用的输出。我正在尝试在上面的 javascript 中获取“名称”:

{
    "@odata.context": "$metadata#Object",
    "value": [
        {
            "@odata.etag": "W/\"24979988a17d428c\"",
            "Name": "Load Actual",
            "StartTime": "2021-12-23T22:46:24+10:00",
            "DSTSensitive": true,
            "Active": true,
            "ExecutionMode": "MultipleCommit",
            "Frequency": "P1DT00H00M00S",
            "Attributes": {
                "Caption": "Load Actual"
            }
        }
    ]
}

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    setCh(resp) 更改为setCh(resp.value)。当您调用setCh(resp) 时,您将 ch 设置为等于整个响应 json。这意味着它是带有 @odata.contextvalue 键的映射。方法映射不存在于对象上,但存在于数组 resp.value 上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 2021-12-16
      • 2018-04-20
      • 2017-04-13
      相关资源
      最近更新 更多