React:如何在将“this.state.x”用于函数之前等待数据?

新手上路,请多包涵

我目前正在学习 React,有些东西对新手来说并不那么容易……

我有一个简单的组件 renders 这个(注意它呈现一个 li 数组感谢 功能 getSlots ):

 render () {
    return (
        <ul>
          {this.getSlots(this.state.viewing).map(item => <li key={item}>{item}</li>)}
        </ul>
    )
  }

功能 getSlots 是:

 constructor (props) {...}

getSlots (viewing) {

    SOME STUFF...

    const monday = this.state.house.monday

    return SOME STUFF...
  }

componentDidMount () {...}

render () {...}

关键是 getSlots 需要在 componendDidMount 中获取数据才能工作。实际上,此时 getSlots 不起作用(崩溃),因为它在获取数据之前运行( this.state.house.monday 在运行时为“空”)。

在运行之前如何等待数据被获取 getSlots ?谢谢你的线索。

原文由 charnould 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 191
2 个回答

您将需要有条件地渲染。提供加载状态,以在异步请求的数据之前加载。你会想要像下面这样的东西:

 class WrapperComponent extends PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            isLoaded: false,
            data: null
        };
    }

    componentDidMount() {
        MyApiCall.then(
            res => this.setState({
                // using spread operator, you will need transform-object-rest-spread from babel or
                // another transpiler to use this
                ...this.state, // spreading in state for future proofing
                isLoaded: true,
                data: res.data
            })
        );
    }

    render() {
        const { isLoaded, data } = this.state;
        return (
            {
                isLoaded ?
                    <PresentaionComponentThatRequiresAsyncData data={ data } /> :
                    <LoadingSpinner /> // or whatever loading state you want, could be null
            }
        );
    }
}

原文由 Kyle Richardson 发布,翻译遵循 CC BY-SA 3.0 许可协议

constructor() {
  super()
  this.state = { isLoading: true }
}

componentDidMount() {
  ('fetch data').then(() => { this.setState({ isLoading: false }); })
}

render() {
  return (
    <div>
      {!this.state.isLoading && ('your code')}
    </div>
  );
}

像那样的东西。

原文由 Maxim Saenko 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题