[英]How to update React component when async prop promise resolves?
Lets say I have a component that renders a PivotGrid
component. 可以说我有一个呈现
PivotGrid
组件的组件。 This PivotGrid
takes some data, an array of objects. 此
PivotGrid
接收一些数据,即对象数组。
function My_component(props) {
return <PivotGrid dataSource={props.data} />
}
However, the data
prop that I want to pass in is the result of an async function. 但是,我要传递的
data
属性是异步函数的结果。
const get_data = async () => {
return await o(url, options).get('foo').query({})
}
ReactDOM.render(<My_component data={get_data()}/>, document.getElementById('root'));
What happens is that the component renders before the promise from get_data()
is resolved, and the PivotGrid has no data. 发生的情况是该组件在
get_data()
的承诺被解决之前就已呈现,并且PivotGrid没有数据。
What I would like to happen is for the component to re-render when the promise resolves and actually returns data. 我希望发生的事情是,在Promise解析并实际返回数据时重新渲染组件。 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. 我尝试了React的
useState()
变体,将props.data
视为状态变量,以便当promise返回状态时,状态会发生变化,组件也会更新。 But this has not worked yet. 但这还没有奏效。
const [gridData, setGridData] = useState(props.data);
props.data.then((r) => {
setGridData(props.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? 实现此功能的最佳方法是什么,当
prop.data
解析并实际保存我想要的数据时,组件会重新渲染?
Using hooks and the container component for My_component should work. 使用挂钩和My_component的容器组件应该可以工作。
my-component-container.js: 我的分量,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} />
}
In your entry point: 在您的入口点:
import My_component_container from './my-component-container'
ReactDOM.render(<My_component_container />, document.getElementById('root'))
Why not change to a stateful component like below 为什么不更改为如下所示的有状态组件
class My_component extends React.Component {
state = {};
componentDidMount(){
this.get_data()
}
get_data = async () => {
const data = await o(url, options).get('foo').query({});
this.setState({ data });
}
render() {
const { data } = this.state;
return <PivotGrid dataSource={data} />
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.