簡體   English   中英

this.state.names.map 不是 function

[英]this.state.names.map is not a function

這是我的代碼,我只需要從 API 獲取數據並想要 map 它但我做不到我不知道為什么。 我已經瀏覽了所有的視頻教程,但仍然找不到我的問題。

    class App extends Component {
    state = {
        names: [],
        isLoaded: false,
    }
    constructor(props) {
      super(props);
    }
    componentDidMount() {
      fetch("https://dog.ceo/api/breeds/list/all")
      .then(res => res.json())
      .then(name => {
        this.setState({
          names: name,
          isLoaded: true,
        })
      });  
    }
    renderNames() {
    if(this.state.names.length > 0) {
      return this.state.names.map((breed) =>
        <div key={breed.message}>
        {breed.message}
        {breed.status}
        </div>
      )  
    }
    else{
        return;

    render(){

每次我找到這種狀態破壞一切的方式時,這個加載也是一個問題

      if (!this.state.isLoaded)  {
        return <div>loading....</div>
      }
      else{
        return (
          <div className="App">
          <h1>Choose a name of breed</h1>
          {this.renderNames()}


          </div>

this綁定到構造函數中的renderNames 喜歡:

constructor(props) { super(props); this.renderNames = this.renderNames.bind(this) }

或者

renderNames為箭頭 function。 例如

renderNames = () => { //Your code. }

首先要做的事情...重新安排您的代碼..將您的 state 放在構造函數中..然后... Console.log 從 promise 中記錄您的名稱值,看看數據是否實際存在...然后我們將知道下一步去做。

暫無
暫無

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

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