【问题标题】:How to get the updated props immediately after service call in reactjs?reactjs中的服务调用后如何立即获取更新的道具?
【发布时间】:2017-06-28 11:07:59
【问题描述】:

在组件中我想在调用后立即在 props 中获取数据 webapi服务调用并做一些操作,但问题是它不是 立即更新道具,因为我们知道调用将是 异步,那么解决方案是什么?我在组件中的代码就像 这个:-

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,我尝试了两种解决方案:-

  1. 处理页面的生命周期
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");
}
  1. 在渲染中编写代码
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 是我要访问的按钮单击 props 命名为 reportData.But console.log(this.props.reportData);是 第一次给我空值,如果我愿意,第二次 单击然后我们正在获取数据。我们如何管理这个?我已经尝试了以上两种解决方案,但它不起作用。

【问题讨论】:

  • 在数据可用之前禁用按钮。
  • 在获取数据时显示微调器,或渲染为空

标签: reactjs react-redux


【解决方案1】:

简单的答案,你不会^1

如果这确实是一个异步请求,则无法保证数据何时会返回,因此您的组件需要“理解”它可以以“无数据”状态存在。

最简单的形式是:

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 注意:从技术上讲,您可以使用异步函数,但我认为这会使问题复杂化,尤其是在对已经发生的事情没有基本了解的情况下。

【讨论】:

  • 我不想在按钮单击事件上呈现任何 html,我想要一些其他功能,例如打开 pdf、生成 CSV 文件和下载,因此在这种情况下,您的解决方案将失败。请查看更新后的问题。
  • 改变问题的形式很糟糕。无论如何,该解决方案都是正确的——如果报告数据尚未准备好,则无法访问。您的新问题更接近于解决方案 - componentWillReceiveProps 可能是解决问题的方法
【解决方案2】:

在您创建商店的主文件中,您可以像这样发送操作并设置初始值

import configureStore from './store/configureStore;
import {LoadReportData} from './actions/LoadReportData';

const store = configureStore();
store.dispatch(LoadReportData());

【讨论】:

    猜你喜欢
    • 2019-08-24
    • 2016-07-21
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多