在反应组件中未定义 - 但未在行动中
undefined within the react component - but not in action
号召性用语(后端调用)响应是某个数组 - 此处未定义 - 在少数其他情况下,我在数组上进行映射时,我也会看到未定义错误的映射。 componentDidMount 是放置此类调用的正确位置吗?
当我在调度前控制台登录 action creator 时,我得到了响应。
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
}
或定义一个在请求成功后执行的回调。
我认为你的 fetchData()
返回 Promise
即 async
所以你可以从 componentWillReceiveProps()
获取数据,当你有新道具时它会被调用。
componentWillReceiveProps(nextProps){
console.log(nextProps.responseData); //do whatever you want with response
}
因为 componentDidMount()
只被调用一次。这不是用你的 props
做某事的可靠地方。
号召性用语(后端调用)响应是某个数组 - 此处未定义 - 在少数其他情况下,我在数组上进行映射时,我也会看到未定义错误的映射。 componentDidMount 是放置此类调用的正确位置吗?
当我在调度前控制台登录 action creator 时,我得到了响应。
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
}
或定义一个在请求成功后执行的回调。
我认为你的 fetchData()
返回 Promise
即 async
所以你可以从 componentWillReceiveProps()
获取数据,当你有新道具时它会被调用。
componentWillReceiveProps(nextProps){
console.log(nextProps.responseData); //do whatever you want with response
}
因为 componentDidMount()
只被调用一次。这不是用你的 props
做某事的可靠地方。