【问题标题】:undefined within the react component - but not in action在反应组件中未定义 - 但不是在行动
【发布时间】:2016-11-21 20:43:56
【问题描述】:

号召性用语(后端调用)响应是一些数组 - 在此处未定义 - 在我映射数组的其他少数情况下,我也看到未定义错误的映射。 componentDidMount 是放置此类调用的正确位置吗?

当我在调度之前控制台登录操作创建者时,我得到了响应。

componentDidMount() {

    this.props.fetchData(test, foo);
    console.log(this.props.responseData); //getting here undefined
  }

function mapStateToProps(state) {
  return {
    responseData: state.abc.responseData,
  };
}

Mycomp.propTypes = {
  responseData: React.PropTypes.array,
  fetchData: React.PropTypes.func,
};

export default connect(mapStateToProps, actions)(Mycomp);

【问题讨论】:

标签: reactjs react-jsx react-redux


【解决方案1】:

这是未定义的,因为在您尝试记录响应时尚未发出请求 - 它是异步的。

您可以在此处调用操作:

componentDidMount() {
  this.props.fetchData(test, foo);
}

componentWillReceiveProps(props) {
  if (props.responseData) { console.log(props.responseData); } // should be getting the data if the request works
}

或定义在请求成功后执行的回调。

【讨论】:

  • 是的,你是对的,我现在在
    {this.props.data}
    中看到了该值 我在几分之一秒之前看到了一个错误 我看到了错误屏幕“未定义”-如果道具不为空,我如何确保在 reactjs 中...如何添加道具。 responseData 到构造函数/getInitialstate 等,?
  • 试试<div>{this.props.data ? this.props.data : ''}</div>。基本上你想检查它是否未定义,如果不显示它。
  • 试过了,在页面加载之前我仍然看到红屏一秒钟 - 以及一条错误消息....bundle.js:76754 Uncaught TypeError: Cannot read property 'data' of undefined( …)
  • 您确定错误出在渲染方法中吗?或者您是否在 this.props.data 实际存在之前在其他任何地方使用它?
  • 嘿,对不起,我很抱歉,我正在检查 if 中的内部值 - 而不是高级对象 - 现在为我工作..感谢您的帮助。
【解决方案2】:

我认为您的fetchData() 正在返回Promise,即async

所以你可以从componentWillReceiveProps() 获取数据,当你有新的道具时会调用它。

componentWillReceiveProps(nextProps){
   console.log(nextProps.responseData); //do whatever you want with response
}

因为componentDidMount() 只被调用一次。用你的props 做某事不是可靠的地方。

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2018-10-06
    • 1970-01-01
    • 2019-08-25
    • 2021-06-24
    相关资源
    最近更新 更多