简体   繁体   English

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

[英]How can I pass state to action to fetch API?

so im new in redux and I need bit of help with my homework. 所以我是redux的新手,我的作业需要一些帮助。 I have a drop down with couple of choices and the choice that user select needs to be passed to state (already have this working and state is updating when user select something new) and then to action that can fetch data with '/stats/${userChoice}' . 我有一个下拉有两个选项和用户选择需要传递到状态的选择(当用户选择新的东西时已经有这个工作和状态正在更新)然后到可以用'/stats/${userChoice}'获取数据的操作'/stats/${userChoice}' But i have no idea how to do this at all. 但我根本不知道如何做到这一点。

actions/index.js: 动作/ 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: 组件/ 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)

under "selectAuthor" I have my state that I need to pass to this action API 在“selectAuthor”下我有我的状态,我需要传递给这个动作API

You can achieve this by calling the API directly with the event target value : 您可以通过使用事件目标值直接调用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)
}

if you wish to still save it on the react state you can do the setState first and then the API call with (this.state.selectedAuthor) instead of (e.target.value) 如果你仍希望将它保存在react状态,你可以首先执行setState,然后使用(this.state.selectedAuthor)而不是(e.target.value)执行API调用。

You already map dispatch to fetchAuthorsStats thunk in your component so that means you can just use it in onAuthorSelect (or anywhere else you need - like on form submit) and pass it a parameter with the selectedAuthor. 您已经将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