簡體   English   中英

Console.log打印兩次,並且地圖在reactjs / mobx項目中不起作用

[英]Console.log prints twice and map doesn't work in reactjs/mobx project

我的Mobx商店中有以下提取請求:

 getAllLegoParts = action("get all lego", () => {
this.legoParts = fromPromise(
  fetch("http://localhost:8000/LegoPieces", {
    method: "GET",
    cache: "no-store"
  }).then(response => response.json())
 );
 });
}

我在下面的ReactJS類中使用它:

class ViewLegos extends Component {
 constructor(props) {
 super(props);
 this.props.store.getAllLegoParts();
}

render() {
console.log(this.props.store.legoParts.value);
return (
  <div>
    <table>
      <thead>
        <tr>
          <th>Piece</th>
          <th>Type</th>
        </tr>
      </thead>
      <tbody>
        {this.props.store.legoParts.map(legoPart => (
          <tr key={legoPart.id}>
            <td>{legoPart.piece}</td>
            <td>{legoPart.piece}</td>
            <td>{legoPart.type}</td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);
}
}

export default inject("store")(observer(ViewLegos));

但是我有兩個問題:

  1. Console.log打印兩次-一種情況是未定義打印,第二種情況是打印對象數組(這是我想要的)。

  2. 我收到一條錯誤消息:

     TypeError: this.props.store.legoParts.map is not a function 

感謝您的幫助!

是否可以等到組件安裝好后再獲取其顯示數據? 以下是一些偽代碼可能會有所幫助:

class ViewLegos extends Component {

   componentDidMount() { fetchLegos() }

   render() {
     const allowRender = this.props.store.legoParts && this.props.store.legoParts.length

     if (allowRender) {  
       // display lego data
     }

     return null
   }

}

在此示例中,我們等待組件安裝,獲取數據並僅在存在時顯示它。

查看您的代碼,看起來好像您需要更具防御性,並且在legoParts尚未定義時處理組件顯示。 由於您的異步獲取操作將在渲染之前完成,因此不會在一開始就定義它們。

暫無
暫無

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

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