【问题标题】:ReactJS what is the proper way to wait for prop to load to avoid crashing my page?ReactJS等待道具加载以避免崩溃我的页面的正确方法是什么?
【发布时间】:2022-01-08 19:00:12
【问题描述】:

所有,

我正在为自己建立一个本地股票网站。目前我有一个与我的 tomcat 实例通信以获取股市数据的商店,这完美无缺。

在我的前端我试图显示我的数据,但有时它可以工作,有时它不工作,我得到一个“这个子道具不存在”所以这就是我实现的:

try{
          cellRend = this.cellRenderer;
          columnLen = this.props.selectedStock.Revenue.length;
          this.state.isLoading = false
        }catch(error){ 
           cellRend = this.cellRendererEmpty;  
           columnLen = 10;
        }
        if (this.state.isLoading === true){
            return <div>Loading!</div>
        }

其中 cellRenderer 是我的表,cellRendererEmpty 是一个空表。

这种工作,有时它只会显示加载!永远。所以我的问题是等待道具的正确方法是什么?

这是我的完整代码:


const dispatchToProps = dispatch => {
    return{
      getSelStock: (stockId) => dispatch(stockActions.getSelStock(stockId))  
    };
}


class stockPage extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            columnLen:10,
            data:null,
            isLoading:true
        }
        console.log(this.props.isLoading)
        this.cellRenderer = this.cellRenderer.bind(this);
        this.render = this.render.bind(this);
    }
    
    cellRenderer({ columnIndex, key, rowIndex, style }) {   
            return (
      <div className={"app"} key={key} style={style}>
          <span></span>
        {rowIndex === 0 ? (`${this.props.selectedStock.Revenue[columnIndex].date}`) : (
          <span>{`${this.props.selectedStock.Revenue[columnIndex].value}`}</span>
        )}
      </div>
    );
        
    }
    
    cellRendererEmpty({ columnIndex, key, rowIndex, style }) {
            return (
      <div className={"app"} key={key} style={style}>
        {rowIndex === 0 ? (`${columnIndex}`) : (
          <span>{`${columnIndex}`}</span>
        )}
      </div>
    );
        
    }
    
    
    
    
    render() { 
        var cellRend, columnLen
                console.log("Hey")
       this.props.getSelStock(this.props.match.params.stockId);        
        try{
          cellRend = this.cellRenderer;
          columnLen = this.props.selectedStock.Revenue.length;
          this.state.isLoading = false
        }catch(error){ 
           cellRend = this.cellRendererEmpty;  
           columnLen = 10;
        }
        if (this.state.isLoading === true){
            return <div>Loading!</div>
        }
        return(
                
                <div>
                <h1>{this.props.match.params.stockId}</h1>
                    <AutoSizer disableHeight>
      {({ width }) => (
        <MultiGrid
          cellRenderer={cellRend}
          columnWidth={125}
          columnCount={this.state.columnLen}
          enableFixedColumnScroll ={1}
          enableFixedRowScroll ={1}
          fixedColumnCount
          fixedRowCount
          height={300}
          rowHeight={70}
          rowCount={2}
          style={STYLE}
          styleBottomLeftGrid={STYLE_BOTTOM_LEFT_GRID}
          styleTopLeftGrid={STYLE_TOP_LEFT_GRID}
          styleTopRightGrid={STYLE_TOP_RIGHT_GRID}
          width={width}
          hideTopRightGridScrollbar
          hideBottomLeftGridScrollbar
          hideBottomRightGridScrollbar
        />
      )}
    </AutoSizer>
        </div>
                )
    
    
    }
    
}
export default connect(mapStateToProps, dispatchToProps)(stockPage);

【问题讨论】:

  • this.state.isLoading = false 是错误的。你不能像那样改变状态。拨打setState() 电话。
  • 你的权利我忘了,我将它更新为 this.setState({isLoading: false}) 并且问题仍然存在,有时它可以正常工作(例如,它可以在我的本地笔记本电脑上工作,但是不是我的手机/其他电脑
  • 它有时也无法在我的本地机器上运行,并且卡在“加载”中

标签: javascript reactjs react-redux react-props


【解决方案1】:

根据您的标题,我假设当您的页面加载时,您正在获取数据,然后在页面中使用该数据。但是,在初始加载期间以及仍在进行提取时,您的数据仍然为空,您的应用将崩溃,因为代码期望数据具有它需要使用的值...

您可以做的是在数据获取时,不要显示页面的其余部分(即,您可以只显示一个巨大的微调器 gif),然后在获取完成后更新 isLoading 状态...或者您可以为数据设置一个初始值,这样页面就不会在加载时崩溃...

编辑: 因此,根据您的评论,使用反应生命周期解决了您的问题...无论如何,只想添加您可能想要使用 async/await 而不是 setTimeout 就像您在评论中所做的那样。这就是 async/await 的代码可能的样子在生命周期中...

componentDidMount() {
    const fetchData = async () {
        await this.props.getSelStock() // your dispatch

        // the state you want to update once the dispatch is done
        this.setState({isLoading: false}) 
    }

    fetchData();
}

【讨论】:

  • 谢谢,在我的第一个代码 sn-p 中,这正是我想要做的,但问题是有时它会永远保持加载,有时它会工作。有时手动刷新等......你看到我做错了什么吗?谢谢!
  • 您的第一个代码 sn-p 在渲染函数中,尝试在您只想在初始页面加载期间运行的代码上使用 componentDidMount。获取数据然后将 isLoaded 设置为 true 的逻辑通常属于那里...
  • 好的,所以我添加了 componentDidMount() { this.props.getSelStock(this.props.match.params.stockId); setTimeout(() => { this.setState({ isLoading: 'false' }); }, 6000);只需等待 6 秒就可以了,有没有等待道具加载?感谢您的帮助顺便说一句
  • 如果我理解正确的话,它可以与 setTimeout 一起按预期工作,而您只是想要它,而不是 setTimeout,isLoading:false 将在加载道具的那一刻运行?
  • 没错! paren 道具在孩子之前加载,那么我该如何等到孩子加载? (即 this.selectedStock 已加载,但 this.selectedStock.Revenue 尚未加载)
猜你喜欢
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
  • 2017-09-13
  • 2020-11-15
相关资源
最近更新 更多