首页 > 解决方案 > 如何在 React 应用程序中呈现服务器响应

问题描述

我正在尝试从服务器获取数据,然后经过一些解析,将其呈现在组件的表中。但问题是服务器的响应太晚了,我的表格没有显示。如何从服务器和模板同步我的数据?

谢谢

class TFSBuilds extends React.Component {

    constructor(){
        super(props);
        this.state = {
            builds: []

        };

    }
      componentDidMount() {

         AzureService.send("ObCloud").then((data)=>{
             let groupedData = this.groupBy(data.value, obj => obj.definition.id)
             this.createChartObjects(groupedData)    
         });
    }

     createChartObjects(groupedRecords) {
        const arr = [];
        for (let [k, v] of groupedRecords) {
            if(v && k){

                 this.state.builds.push(v[0]);
            }
        }
        return arr;
    }
    render() {
        const { builds } = this.state
        if (builds.length <= 0) { return null }
        return (
            <div className = "build-status" >
                <table className="table table-hover">
                    <thead>
                    <tr>
                        <th scope="col">By</th>
                        <th scope="col">When</th>
                        <th scope="col">Status</th>

                    </tr>
                    </thead>
                    <tbody>
                    {
                       builds.map(el =>
                            <tr>
                            <th scope="row">{el.requestedBy.displayName}</th>
                            <td>{el.requestedBy.date}</td>
                            <td>{el.requestedBy.status}</td>
                        </tr>)
                    }
                    </tbody>
                </table>

            </div>
        )
    }

}

export default TFSBuilds;

标签: javascriptreactjs

解决方案


您遇到的问题是在状态更新后您没有触发另一个渲染。你可以通过调用 setState() 来改变状态,而不是改变状态对象。

你需要做的就是改变这个:

this.state.builds.push(v[0]);

对此:

this.setState({ builds: this.state.builds.concat(v[0]) });

推荐阅读