繁体   English   中英

如何将状态传递给动作以获取API?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM