代码之家  ›  专栏  ›  技术社区  ›  Yusuf Yeşilyurt

React Axios=>无法读取未定义的属性(读取“长度”)

  •  1
  • Yusuf Yeşilyurt  · 技术社区  · 4 年前

    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>
        )  
    

    此代码可能有什么问题?

    2 回复  |  直到 4 年前
        1
  •  2
  •   Ploppy    4 年前

    model useState()

    在第一次渲染期间,您没有传递任何消息 没有定义。

    一种解决方案是将模板更改为:

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

    或者让它有条件

    {model && (
      <>
        {model.slug} : {model.name}
      </>
    )}
    
        2
  •  0
  •   Sai Kranthi    4 年前

    除了上面@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>
    )  
    

    推荐文章