【问题标题】:How to render data in react getting undefined state?如何在获得未定义状态的反应中呈现数据?
【发布时间】:2019-06-09 18:32:24
【问题描述】:

我在 componentDidMount 中获取数据,但我在初始渲染期间未定义,并且再次渲染发生,并且在此期间状态变量被填充。现在,当它不是未定义的并且在填充之后我想解构它并在我的组件中显示数据。

注意:getProjectDetails() 生成一个 GET 请求来填充数据。

我收到未定义的类型错误名称。

  constructor(props) {
            super(props);
            this.state = {
               projectDetails: ''
            };
        }

    componentDidMount() {
            getProjectDetails(this.props.logged_in_user, this.props.projectId)
                .then( res => {
                    this.setState({projectDetails: res});
                })
                .catch(err => {
                    console.log('Error: ' + err);
                })
        }

    //Inside render()

    render() {
            console.log('Project details from API endpoint: ', this.state.projectDetails.project)

            const { projectDetails } = this.state;
            console.log('Destructure: ', projectDetails);

            const project = this.state.projectDetails.project;

    let {  
                name,
                location,
                city,
                builder_name } = project;

【问题讨论】:

  • 您可以尝试在 componentWillMount 方法中设置 Async 函数调用,这样可能会更好。
  • 我使用了 componentWillMount 但仍然遇到同样的错误
  • 你的初始状态没有对象项目。

标签: javascript reactjs


【解决方案1】:

如果设置了状态,您可以检查以下内容:

render() {
    if(this.state.projectDetails === ''){
        return <div>Loading</div>;
    }
    else{
        return <div>{this.state.projectDetails.project}</div>
    }
}

所以只要状态为false,就会返回Loading,如果有值,则返回this.state.projectDetails.project。我希望这会有所帮助。

编辑: render 方法将被调用两次,在获取数据之前,然后在设置状态之后。所以这只会返回数据,如果它真的设置了。

【讨论】:

  • 您的回答很有效,谢谢。我想问你,在处理初始渲染的未定义状态时,我应该总是添加 if 语句,说如果我不这样做;不这样做,那么我会得到类型错误
  • 任何其他方式来处理这种未定义的状态情况?还是这是最好的情况?
  • 在你的观点上,我只是想让你的初始状态不是''。我会将其设为 undefined 或 null,因此您可以将其设为 if(!this.state.projectDetails)
猜你喜欢
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2019-06-05
  • 1970-01-01
  • 2018-08-27
  • 2021-03-05
  • 1970-01-01
相关资源
最近更新 更多