在组件中我希望在调用后立即在props中获取数据 webapi服务调用并做一些操作,但问题是它不是 立即更新道具,因为我们知道呼叫将是 async,那么解决方案是什么?我在组件中的代码就像 此: -
openPreviewClick=(event) => {
this.props.GetReport();
console.log(this.props.reportData);
}
function mapStateToProps (allReducers) {
return {reportData: allReducers.reportData
}}
const matchDispatchToProps = (dispatch) => ({
GetReport: () => dispatch(LoadReportData())
})
export default connect(mapStateToProps, matchDispatchToProps)(MyContainer)
现在我必须打开一个pdf,我试过两个解决方案: -
- 处理页面的生命周期
醇>
componentWillReceiveProps(nextProps) {
if(nextProps.reportPath!=undefined){
window.open(nextProps.reportPath,"thePop","menubar=1,resizable=1,scrollbars=1,status=1,top=280,width=850,height=600");
}
- 在渲染中编写代码
醇>
render () {
if(this.props.reportPath!=undefined && this.props.reportPath!=""){}
window.open(this.props.reportPath,"thePop","menubar=1,resizable=1,scrollbars=1,status=1,top=280,width=850,height=600");
}
openPreviewClick是我想要访问的按钮单击 名为reportData.But的props.log(this.props.reportData);是 第一次给我空值,如果我愿意,第二次给我 点击,然后我们得到数据。我们如何管理这个?我已经尝试过以上两个解决方案,但它无法正常工作。
答案 0 :(得分:2)
简单回答,你不要
如果这确实是异步请求,则无法保证数据何时返回,因此您的组件需要了解"了解"那可以存在于没有数据的情况下。州。
最简单的形式是:
render() {
if( ! this.props.reportData) return null;
// normal render code, at this point we have data
return <div>{this.props.reportData.map(foo, ...)}</div>
}
更好的形式,就像:
render() {
if( ! this.props.reportData) {
return <div><img src="loading.gif" /></div>;
}
// normal render code, at this point we have data
return <div>{this.props.reportData.map(foo, ...)}</div>
}
^ 1注意:您可以在技术上使用异步函数,但我觉得这会使问题复杂化,尤其是在没有基本了解已经发生的事情的情况下。
答案 1 :(得分:0)
在创建商店的主文件中,您可以调度操作并设置初始值,就像
一样import configureStore from './store/configureStore;
import {LoadReportData} from './actions/LoadReportData';
const store = configureStore();
store.dispatch(LoadReportData());