在反应组件中未定义

编程入门 行业动态 更新时间:2024-10-26 23:33:32
在反应组件中未定义 - 但不在行动中(undefined within the react component - but not in action)

有一个行动呼吁(后端调用)响应是一些数组 - 在这里得到未定义 - 在少数其他情况下我在数组上映射我也看到了未定义错误的映射。 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);

Have a call to action (backend call) response is some array - getting undefined here - in few other cases where I am mapping over the array I am seeing map of undefined error as well. Is componentDidMount right place to put such calls?

I get the response back when I console log in action creator before dispatching.

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);

最满意答案

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

您可以在此处调用操作:

componentDidMount() { this.props.fetchData(test, foo); } componentWillReceiveProps(props) { if (props.responseData) { console.log(props.responseData); } // should be getting the data if the request works }

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

It is undefined because the request has not been made at the time you're trying to log the response – it's async.

You can either call the action in here:

componentDidMount() { this.props.fetchData(test, foo); } componentWillReceiveProps(props) { if (props.responseData) { console.log(props.responseData); } // should be getting the data if the request works }

or define a callback that is executed after the request was successful.

更多推荐

本文发布于:2023-08-04 15:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417621.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   中未   定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!