【问题标题】:React-Axios => Cannot read properties of undefined (reading 'length')React-Axios => 无法读取未定义的属性(读取“长度”)
【发布时间】:2025-11-29 00:05:02
【问题描述】:

我正在尝试从 API 检索一些数据。当我控制数据时,它工作正常:

import axios from 'axios';

export default function Model() {
  
    const url = "api.blabla.com/blabla"
    const [model, setModel] = useState()
    useEffect(() => {
      const axiosPosts = async () => {
        const response = await axios(url)
        setModel(response.data)
      };
      axiosPosts();
    }, []);

   console.log(model.slug) //prints the slug!!

    
    return (
      <div>
       {model.slug} : {model.name} // TypeError slug undefined
      </div>
    )  

这段代码有什么问题?

【问题讨论】:

  • 长度在哪里?请注意,模型的 initial 状态确实是未定义的。
  • 感谢您的编辑,您的问题已解决。

标签: javascript reactjs api axios use-effect


【解决方案1】:

api 响应需要时间,所以在开始时 model 被分配了您传递给 useState() 钩子的参数值​​。

你没有传递任何东西,所以在第一次反应渲染期间 model 是未定义的。

一种解决方案可能是将您的模板更改为:

{model?.slug} : {model?.name}

或者让它有条件

{model && (
  <>
    {model.slug} : {model.name}
  </>
)}

【讨论】:

  • 非常感谢,它现在工作正常。从 API 获取时是否总是需要使用这样的数据,还是有其他方法(可能是更好的做法)?
  • 更好的做法是创建另一个只有一个角色的组件:渲染数据。您只能在数据可用时显示此组件,就像我在第二个示例中向您展示的那样。
【解决方案2】:

在上面@ploppy 的回答中添加更多内容,这里的常见模式是

import axios from 'axios';

export default function Model() {

const url = "api.blabla.com/blabla"
const [status, setStatus] = useState("idle");
const [model, setModel] = useState({
  slug: "",
  name: ""
})
useEffect(() => {
  setStatus("pending");
  const axiosPosts = async () => {
    try{
    const response = await axios(url)
    setModel(response.data)
    setStatus("resolved")
   }catch(error){
    console.log(error);
    setStatus("rejected");
   }
  };
  axiosPosts();
}, []);

console.log(model.slug) //prints the slug!!

if(status === "pending"){
    return (<div>Loading...</div>)
}
if(status === "rejected"){
    return (<div>Something went wrong!</div>)
}
return (
  <div>
   {model.slug} : {model.name} // TypeError slug undefined
  </div>
)  

这使您能够更好地处理 API 调用及其响应。

【讨论】: