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