【问题标题】:How to setState with a promise before render?如何在渲染之前用承诺设置状态?
【发布时间】:2020-06-17 08:36:47
【问题描述】:

我在 props 中有承诺:this.props.getProfile(),我想在 render() 之前将 promise 中的响应值设置为状态

我尝试过使用UNSAFE_componentWillMountgetDerivedStateFromProps,但它总是响应未决的承诺。

这是我对UNSAFE_componentWillMount的尝试:

    UNSAFE_componentWillMount(){
        this.setState({profile: this.getProfile()})
    }
    getProfile=()=>{
        return this.props.getProfile()
        .then(res =>{
            if (res.type === 'ERROR_MESSAGE') {
                return null;
            }
            return res.payload
        });
    }

这是我对getDerivedStateFromProps的尝试:

    static getDerivedStateFromProps (props, state){
        let a = props.getProfile()
        .then(res =>{
            if (res.type === 'ERROR_MESSAGE') {
                return null;
            }
            return res.payload
        });
        console.log(a);
        if(a.profile !== state.profile)
            return {profile: a};
    }

【问题讨论】:

  • 在渲染组件之前解决promise,而不是在组件内执行。这样你就不用提供 Promise 作为道具,而是准备好渲染的最终值。
  • 怎么办,我的props只是一个axios请求,不是组件

标签: reactjs promise


【解决方案1】:

您可能会认为,在给定的承诺中,一旦您在 then 方法中返回某些内容,您将立即获得该值,而实际上您正在返回其他承诺。要解决您有两种标准方法,请使用async/await 或将另一个then 链接到promise。

getDerivedStateFromProps 不用于数据获取,因为您可以看到一个很好的讨论 here

异步\等待

async componentDidMount() {
  const profile = await this.props.getProfile()
  this.setState({ profile })
}

承诺链

componentDidMount() {
  this.props
    .getProfile()
    .then(profile => this.setState({ profile }))
}

【讨论】:

  • 感谢您的帮助,但 componentDidMount() 在 render() 之后,然后在渲染完成后解析。我的问题是render()之前的setState@
  • 你不能通过异步方法调用来做到这一点。您甚至试图为此使用不安全的弃用方法,这很糟糕。正确的方法是在获取状态时使用 didmount 和条件渲染。或在获取状态后在父级调用 fetch 并有条件地渲染您的孩子。我发布的链接是 react 的领导创建者的回应,明确告诉不要为此使用这些方法。很抱歉,我不能给你一个违反 react 原则的答案。
猜你喜欢
  • 1970-01-01
  • 2020-03-10
  • 2021-03-03
  • 2021-07-20
  • 1970-01-01
  • 2017-11-11
  • 2017-10-25
  • 2018-11-29
  • 1970-01-01
相关资源
最近更新 更多