代码之家  ›  专栏  ›  技术社区  ›  Nespony

安慰日志打印两次,映射在reactjs/mobx项目中不起作用

  •  0
  • Nespony  · 技术社区  · 7 年前

    我的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. 安慰日志打印两次-在一种情况下,打印未定义,在第二种情况下,它打印一个对象数组(这就是我想要的)。

    2. 我收到一个错误,说:

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

    感谢您的帮助!

    1 回复  |  直到 7 年前
        1
  •  1
  •   random-forest-cat    7 年前

    是否可以等到组件安装完毕后再提取其显示数据?以下是一些可能有帮助的伪代码:

    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尚未定义的情况下更加防御性地处理组件显示。它们不会在一开始就定义,因为在渲染之前,异步获取不会完成。