![](/img/trans.png)
[英]How to re-render React Component when promise resolves? | How to block render until data loads?
[英]How to update React component when async prop promise resolves?
可以說我有一個呈現PivotGrid
組件的組件。 此PivotGrid
接收一些數據,即對象數組。
function My_component(props) {
return <PivotGrid dataSource={props.data} />
}
但是,我要傳遞的data
屬性是異步函數的結果。
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沒有數據。
我希望發生的事情是,在Promise解析並實際返回數據時重新渲染組件。 我嘗試了React的useState()
變體,將props.data
視為狀態變量,以便當promise返回狀態時,狀態會發生變化,組件也會更新。 但這還沒有奏效。
const [gridData, setGridData] = useState(props.data);
props.data.then((r) => {
setGridData(props.data)
})
諸如此類的嘗試都會失敗。 實現此功能的最佳方法是什么,當prop.data
解析並實際保存我想要的數據時,組件會重新渲染?
使用掛鈎和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'))
為什么不更改為如下所示的有狀態組件
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.