Console.log打印两次,map在reactjs / mobx项目中不起作用

问题描述 投票:0回答:1

我的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

感谢你的帮助!

javascript reactjs mobx mobx-react
1个回答
0
投票

在获取显示数据之前是否可以等到组件已安装?这是一些可能有用的伪代码:

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尚未定义时,您似乎需要更加防御并处理组件显示。由于在渲染之前您的异步提取无法完成,因此它们不会在开头定义。

© www.soinside.com 2019 - 2024. All rights reserved.