简体   繁体   English

反应获取数据然后作为道具传递?

[英]React fetching data then passing as props?

I have a view that contains several components. 我有一个包含几个组件的视图。

class ProfileView extends React.Compnent {
  constructor() {
    super();
    this.state = {
      user: {}
    }
  }
  componentWillMount() {
    fetchData((res) => {
      this.setState({user: res});
    })
  }
  render() {
    return (
      <div>
        <SomeComponent user={this.state.user} />
        <AnotherComponent />
      </div>
    )
  }
}

Since this is making an async call and rendering the state as an empty object on the initial redner, it's causing what I think to be a problem? 由于这是进行异步调用并将状态呈现为初始修改器上的空对象,因此导致我认为是问题吗?

Inside my inner component I have to write validation, which is ok but feels wrong, that is why I am asking this question, is the validation in the example below good practice or am I making a mistake. 在我的内部组件中,我必须编写验证,这是可以的,但是感觉不对,这就是为什么我要问这个问题,是下面示例中的验证是良好实践还是我做错了。

class SomeComponent extends React.Compnent {
  render() {
    if(typeof this.props.user !== 'undefined' && !$.isEmptyObject(this.props.user)) {
      return (
        <div>
          <SomeComponent user={this.state.user} />
          <AnotherComponent />
        </div>
      )
    } else {
      return (
        <div></div>
      )
    }
  }
}

This is the best I could come up with, it works ok but there is a slight jump in my UI because initially I am just rendering a <div> . 这是我能想到的最好的方法,它可以正常工作,但是UI略有跳跃,因为最初我只是渲染<div>

How can I improve my approach, or is this the ideal way to do it? 我该如何改善自己的方法,或者这是理想的方法?

Your implementation is close to what I would do. 您的实现接近我的工作。 I think that the best solution is to initially render a component that indicates to the user that data is being fetched from the server. 我认为最好的解决方案是首先呈现一个组件,该组件向用户指示正在从服务器获取数据。 Once that data comes back, you can update the state of your parent component, which will case the child component to render instead. 一旦数据返回,您就可以更新父组件的状态,这将使子组件处于渲染状态。 A potential solution might look something like this: 潜在的解决方案可能看起来像这样:

function renderChildComponent() {
    const {user} = this.state;

    if (user) {
        return <Child user={user} />;
    }

    return <Loading />;
}

export default class Parent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            user: undefined
        };

    }

    componentDidMount() {
        fetchData(response => {
            this.setState({user: response});
        });
    }

    render() {
        return (
            <div>
                {renderChildComponent.call(this)}
            </div>
        );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM