![](/img/trans.png)
[英]How can i pass a parameters to action method using javascript fetch?
[英]How can I pass state to action to fetch API?
所以我是redux的新手,我的作業需要一些幫助。 我有一個下拉有兩個選項和用戶選擇需要傳遞到狀態的選擇(當用戶選擇新的東西時已經有這個工作和狀態正在更新)然后到可以用'/stats/${userChoice}'
獲取數據的操作'/stats/${userChoice}'
。 但我根本不知道如何做到這一點。
動作/ index.js:
export const fetchAuthorsStats = () => async dispatch => {
const response = await myAPI.get(`/stats/${userChoice}`);
dispatch({ type: 'FETCH_AUTHORS_STATS', payload: response.data })
};
組件/ Dropdown.js:
onAuthorSelect = (e) => {
this.setState({selectAuthor: e.target.value})
};
.
.
.
const mapStateToProps = state => {
return {
authors: state.authors,
selectAuthor: state.selectAuthor,
authorsStats: state.authorsStats
}
};
export default connect(mapStateToProps, { fetchAuthors, selectAuthor, fetchAuthorsStats })(Dropdown)
在“selectAuthor”下我有我的狀態,我需要傳遞給這個動作API
您可以通過使用事件目標值直接調用API來實現此目的:
/// first you update your API call to receive the selected author
export const fetchAuthorsStats = (userChoice) => async dispatch => {
const response = await myAPI.get(`/stats/${userChoice}`);
dispatch({ type: 'FETCH_AUTHORS_STATS', payload: response.data })
};
//then you update your handler function
onAuthorSelect = (e) =>{
this.props.fetchAuthorsStats(e.target.value)
}
如果你仍希望將它保存在react狀態,你可以首先執行setState,然后使用(this.state.selectedAuthor)而不是(e.target.value)執行API調用。
您已經將dispatch映射到組件中的fetchAuthorsStats
thunk,這意味着您可以在onAuthorSelect
使用它(或者您需要的任何其他地方 - 比如表單提交),並使用selectedAuthor傳遞一個參數。
// Added a userChoice param here:
export const fetchAuthorsStats = (userChoice) => async dispatch => {
const response = await myAPI.get(`/stats/${userChoice}`);
dispatch({ type: 'FETCH_AUTHORS_STATS', payload: response.data })
};
onAuthorSelect = (e) => {
this.setState({selectAuthor: e.target.value})
this.props.fetchAuthorsStats(e.target.value);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.