簡體   English   中英

為什么我收到“TypeError: this.state.users.map is not a function”用於已部署的 React 應用程序生產版本

[英]Why am I getting a “TypeError: this.state.users.map is not a function” for deployed production version of React application

使用 React 從 Firestore 數據庫中提取用戶信息,構建了一個 web 應用程序。 在本地運行應用程序時,它運行完美,我可以加載用戶信息。 部署后,我現在收到“TypeError:this.state.users.map 不是函數”消息,頁面甚至無法加載。 為什么它會在部署之前工作,解決方法是什么?

import React, { Component } from 'react';
import AllCoaches from '../components/search/AllCoaches';
import Banner from '../components/layout/banner';
import axios from 'axios';

// MUI Stuff
import Grid from '@material-ui/core/Grid';
import CircularProgress from '@material-ui/core/CircularProgress';


class coaches extends Component {
    state = {
        users: []
      }

  componentDidMount() {
    axios.get('/coaches')
        .then(res => {
            console.log(res.data)
            this.setState({
                users: res.data
            })
        })
        .catch(err => console.log(err));
  }

    render() {
    let coaches = this.state.users ? (
        this.state.users.map((user) => <AllCoaches user={user}/>)
    ) : ( <CircularProgress/> );
      return (
        <Grid container>
        <Banner/>
            {coaches}
        </Grid>
        );  
    }   
}


export default coaches

通過localhost運行時console.log(res.data)的output為:

Array(5) 0: {userId: "name0", bio: info0,} 1: {userId: "name1", bio: info1,} 2: {userId: "name2", bio: info2,} 3: {userId: "name3", bio: info3,} 4: {userId: "name4", bio: info4,} 5: {userId: "name5", bio: info5,}length: 5 proto: Array(0)

部署時 console.log(res.data) 的 output 吐出看起來像我的 index.js 文件的內容?

<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/>.....</body></html>

這里有很多問題,我將指出兩個最明顯的問題:

class 名稱“coaches”需要首字母大寫才能成為有效的 React 組件並呈現給 DOM。

State首先要定義如下,

constructor(props) {
    super(props);

    this.state = {
        users: [],
    };
}

應用這些修復程序后,您的代碼應該可以按預期工作。 如果您現在或將來遇到任何問題,請隨時發表評論,我會幫助您!

1.大寫你的組件名稱

2.要使用 state 你必須調用 super() 方法:

constructor(props) {
super(props);

this.state = {
    users: [],
   };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM