2017-07-03 57 views
0

我正在嘗試將mapDispatchToProps中的動作組合起來。試圖獲取數據和啓動模態對話框後。但我不斷收到無法讀取屬性'然後'的未定義的錯誤。Redux:無法讀取未定義的屬性'then'

有人可以解釋我,我做錯了什麼?

mapDispatchToProps:

const mapDispatchToProps = dispatch => ({ 
    onClick: id => { 
    // console.log(fetchThing(id)) returns undefined 
    dispatch(fetchThing(id)).then(() => { 
     dispatch(showModal()) 
    }) 
    } 
}) 

終極版動作:

export const fetchThing =() => { 
    const request = axios.get(URL_API) 

    return dispatch => { 
    request.then(response => { 
     dispatch({ type: ACTION_FETCH, payload: response.data }) 
    }) 
    } 
} 
+1

爲什麼你有急件內如此多的調度和你爲什麼調度的隨機函數的結果?通常,reducer應該是純粹的函數,不需要異步調用,所以我並不感到驚訝,你會得到某些未定義的東西。也許張貼完整的文件,以確切看到派遣正在做什麼。 –

回答

0

你爲什麼不使用redux-thunk?這樣,您可以寫你的行動像:

export const fetchThing = dispatch => axios.get(URL_API) 
    .then(response => dispatch({ type: ACTION_FETCH, payload: response.data })) 

Redux thunk中間件會做所有的東西給你,你不需要做,每次你需要的mapDispatchToProps內異步操作。

0

mapDispatchToProps不應該有副作用。這應該只是顧名思義,並將行動聯繫起來。這應該是:

const mapDispatchToProps = { 
    fetchThing: yourAction.fetchThing, 
    showModal: yourAction.showModal, 
}; 

export default connect(null, mapDispatchToProps)(YourComponent); 

然後在你的(可能)按鈕:

<button type="button" onClick={this.handleClick} /> 

// this can be an asynchronous function, or you can just handle it in the action. 
handleClick = async id => { 
    await this.props.fetchThing(id); 
    this.props.showModal(); 
}; 
+0

可以使用任何你喜歡的,例如'.then'等。 – DKo

相關問題