在反应组件中未定义 - 但没有在行动

问题描述:

有一个调用动作(后端调用)响应是一些数组 - 在这里得到未定义 - 在其他情况下,我正在映射数组,我看到未定义的错误地图为好。 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); 
+0

想必'fetchData'是异步的吧?所以它不会像下一行 – azium

+0

看到这个问题并接受答案。我认为你会发现它有帮助https://stackoverflow.com/questions/39381378/whats-the-best-way-to-deal-with-undefined-props-in-react-js –

它是未定义的,因为请求在您尝试登录响应时没有进行 - 它是异步的。

您可以拨打行动在这里:

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

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

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

+0

是的,你是对的,我看到现在在

{this.props.data}
的价值我刚才看到一个错误只有几分之一秒我看到错误屏幕'未定义' - 如何确保在reactjs如果道具不是空的...如何添加道具。 responseData构造函数/ getInitialstate等等,? – monkeyjs
+0

尝试'

{this.props.data ? this.props.data : ''}
'。基本上你想检查它是否未定义,如果不显示它。 –
+0

尝试过,我仍然在页面加载前看到红色屏幕一秒钟 - 并显示错误消息.... bundle.js:76754 Uncaught TypeError:无法读取未定义的属性“数据” – monkeyjs

我觉得你fetchData()正在恢复Promise这是async

所以你可以从componentWillReceiveProps()当过你有新的道具这就是所谓的数据。

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

由于componentDidMount()只被调用一次。这是不可靠的地方做你的props