2016-11-21 52 views
0

有一個調用動作(後端調用)響應是一些數組 - 在這裏得到未定義 - 在其他情況下,我正在映射數組,我看到未定義的錯誤地圖爲好。 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 –

回答

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 
} 

或定義執行回調請求後成功。

+0

是的,你是對的,我看到現在在

{this.props.data}
的價值我剛纔看到一個錯誤只有幾分之一秒我看到錯誤屏幕'未定義' - 如何確保在reactjs如果道具不是空的...如何添加道具。 responseData構造函數/ getInitialstate等等,? – monkeyjs

+0

嘗試'

{this.props.data ? this.props.data : ''}
'。基本上你想檢查它是否未定義,如果不顯示它。 –

+0

嘗試過,我仍然在頁面加載前看到紅色屏幕一秒鐘 - 並顯示錯誤消息.... bundle.js:76754 Uncaught TypeError:無法讀取未定義的屬性「數據」 – monkeyjs

0

我覺得你fetchData()正在恢復Promise這是async

所以你可以從componentWillReceiveProps()當過你有新的道具這就是所謂的數據。

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

由於componentDidMount()只被調用一次。這是不可靠的地方做你的props