API尚未响应时如何使用无状态组件的反应? [英] How to use react stateless component when API response didn't got yet?

查看:56
本文介绍了API尚未响应时如何使用无状态组件的反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Laravel中使用React,并且正在尝试构建一个简单的FriendsList组件以显示来自API的数据. 问题在于,父(配置文件)组件在获取数据之前已完成加载,因此FriendsList组件返回错误,因为道具第一次为空.重要的是要说,无论API响应如何-父(配置文件)组件都可以正常工作,第一次将其加载为空-然后添加数据.

I'm working with react in Laravel, and i'm trying to built a simple FriendsList component to display data from API. The problem is that the Parent (Profile) component is finish loading before it's get the data, so the FriendsList component return an error, because the props are empty for the first time. It's important to say that regardless of the API response - the parent (Profile) component works well, it's loaded for the first time empty - and then the data is adding.

Api通话

 export const getProfile = () => {
 return axios
     .get('api/profile', {
        headers: { Authorization: `Bearer ${localStorage.usertoken}` }
     })
    .then(response => {
        // console.log(response.data)
        return response.data
    })
    .catch(err => {
        console.log(err)
    })
 }

父组件

        import React, { Component } from 'react'
        import { getProfile } from './UserFunctions'
        import FriendsList from './FriendsList';

        class Profile extends Component {
            constructor() {
                super()
                this.state = {
                    name: '',
                    hobbies: '',
                    user_bday: '',
                    members: [],
                    error: '',

                }

            }

            componentDidMount() {

                getProfile().then(res => {
                    //   console.log(JSON.parse(res))
                    this.setState({
                        name: res.user.name,
                        hobbies: res.user.hobbies,
                        user_bday: res.user.user_birthday,
                        related_friends: res.user.related_friends,
                        members: res.user.members,

                    })

                })
            }


            render() {

                return (
                    <div className="container">
                        <div className="jumbotron mt-5">
                            <div className="col-sm-4 mx-auto">
                                <h1 className="text-center">PROFILE</h1>
                            </div>
                            <table className="table col-md-4 mx-auto">
                                <tbody>
                                    <tr>
                                        <td>Name</td>
                                        <td>{this.state.name}</td>
                                        <td>{this.state.hobbies}</td>
                                        <td>{this.state.user_bday}</td>

                                    </tr>
                                </tbody>
                            </table>
                            <FriendsList members={this.state.members}> 
       </FriendsList>
                        </div>
                    </div>
                )
            }
        }

        export default Profile

    import React from 'react';
     class FriendsList extends React.Component {

      render() {
        console.log(this.props)
        const { members } = this.props;
        const listmembers = members.map((item, index) => (
          <li key={item + index}>{item.name}</li>
        ));
        return (
          <div>
            {listmembers}
          </div>
        );
      }
    }
    export default FriendsList

推荐答案

有两种解决方法.

第一种方法:

class Profile extends Component {
  render() {
    // check if your `state` has all the necessary values
    // before rendering your JSX

    const { name, hobbies, user_bday, members } = this.state
    const shouldRender = name !== '' && 
      hobbies !== '' &&
      user_bday !== '' &&
      Array.isArray(members) && members.length > 0

    if (!shouldRender) {
      return null;
    }
    return (...)
  }
}

这样,仅当state具有所需的所有内容时,才渲染JSX.

This way, you're only rendering JSX when your state has everything that you need.

第二种方法:

class Profile extends Component {
  constructor() {
    // ...
    this.setState = {
      members: []
    }
  }
}

将您的members设置为一个空数组,而不是一个空字符串,这样,当您将其作为prop传递给FriendList组件时,调用this.props.friends.map实际上是正确的,但不会成功.因为数组最初是空的,所以不渲染任何东西.

Set your members to an empty array, rather than an empty string, so that way when you're passing it as prop to FriendList component, calling this.props.friends.map is actually correct, but it won't render anything since the array is initially empty.

此外,看起来您永远不会在API调用完成后更新members:

Also, it looks like you are never updating your members after your API call finishes:

componentDidMount() {
  getProfile().then(res => {
    this.setState({
      name: res.user.name,
      hobbies: res.user.hobbies,
      user_bday: res.user.user_birthday,
      related_friends: res.user.related_friends,
    })
  })
}

因此,您的members实际上保留为空字符串.确保使用正确的类型更新状态,在这种情况下,该类型应该是数组.

So your members actually stays as an empty string. Make sure your updating your state with the right type, which in this case should be an array.

这篇关于API尚未响应时如何使用无状态组件的反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆