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

How can I pass state to action to fetch API?

所以我是 redux 的新手,我的作业需要一些帮助。我有一个下拉列表,有几个选择,用户 select 需要传递给状态的选择(已经有这个工作,当用户 select 有新的东西时状态正在更新)然后可以采取行动使用 '/stats/${userChoice}' 获取数据。但我根本不知道该怎么做。

actions/index.js:

export const fetchAuthorsStats = () => async dispatch => {
    const response = await myAPI.get(`/stats/${userChoice}`);

    dispatch({ type: 'FETCH_AUTHORS_STATS', payload: response.data })
};

components/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)
}

如果您仍希望将其保存在反应状态,您可以先执行 setState,然后使用 (this.state.selectedAuthor) 而不是 (e.target.value)[= 调用 API 11=]

您已经将分派映射到组件中的 fetchAuthorsStats thunk,这意味着您可以在 onAuthorSelect 中使用它(或您需要的任何其他地方 - 例如表单提交)并传递给它一个参数与选定的作者。

// 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);
};