异步承诺解决时如何更新React组件? [英] How to update React component when async prop promise resolves?

查看:55
本文介绍了异步承诺解决时如何更新React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一个呈现 PivotGrid 组件的组件.此 PivotGrid 接收一些数据,即一个对象数组.

Lets say I have a component that renders a PivotGrid component. This PivotGrid takes some data, an array of objects.

function My_component(props) {
    return <PivotGrid dataSource={props.data} />
}

但是,我要传递的 data 道具是异步函数的结果.

However, the data prop that I want to pass in is the result of an async function.

const get_data = async () => {
    return await o(url, options).get('foo').query({})
}

ReactDOM.render(<My_component data={get_data()}/>, document.getElementById('root'));

发生的事情是该组件在解析 get_data()中的承诺之前呈现,并且PivotGrid没有数据.

What happens is that the component renders before the promise from get_data() is resolved, and the PivotGrid has no data.

我希望发生的事情是,当承诺解决并实际返回数据时,重新渲染组件.我已经尝试了React的 useState()的变体,将 props.data 视为状态变量,以便当promise返回状态时,组件会更新.但这还行不通.

What I would like to happen is for the component to re-render when the promise resolves and actually returns data. I've tried variations of React's useState() to treat props.data as a state variable, so that when the promise returns the state would change the the component would update. But this has not worked yet.

const [gridData, setGridData] = useState(props.data);
props.data.then((r) => {
    setGridData(props.data)
})

上述所有尝试均会失败.实现此功能的最佳方法是什么,当 prop.data 解析并实际保存我想要的数据时,组件会重新渲染?

Attempts like the above all fail. What is the best way to achieve this functionality, where the component re-renders when prop.data resolves and actually holds the data I want?

推荐答案

使用挂钩和My_component的容器组件应该可以工作.

Using hooks and the container component for My_component should work.

my-component-container.js:

my-component-container.js:

import React, {useState, useEffect} from 'react'
import My_component from './my-component'

export default () => {
   const [data, setData] = useState(null)
   useEffect(async () => {
     const fetchData = async () => {
         const result = await o(url, options).get('foo').query({})

         setData(result);
     };

    fetchData();
   }, [])

   return <My_component dataSource={data} />
}

在您的入口点:

import My_component_container from './my-component-container'

ReactDOM.render(<My_component_container />, document.getElementById('root'))

这篇关于异步承诺解决时如何更新React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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