如何在 redux 中使用 API 调用操作? [英] How to work with API call action in redux?
问题描述
我是 redux 的新手,我正在尝试让它与我的应用程序一起使用,但是我在理解如何使用其中的异步操作时遇到了问题.我有 api 调用的操作.一旦我的其他状态不为空,就应该调用此操作.我没有犯任何错误,但我认为我的操作没有被调用,因为数据是空的.任何人都可以帮助理解我做错了什么吗?
I am new to redux and I am trying to make it work with my application, but I have problems with understanding how to work with async actions in it. I have action that is api call. This action should be called as soon as my other state is not empty. I do not get any mistakes but do not think that my action is called since the data is empty. Can anybody help to understand what I am doing wrong?
这是我的 actions.js.wordsFetchData 是我需要调用的操作:
Here is my actions.js. The wordsFetchData is the action I need to call:
export function wordsFetchDataSuccess(items){
return{
type: 'WORDS_FETCH_DATA_SUCCESS',
items
};
}
export function wordsAreFetching(bool){
return{
type: 'WORDS_ARE_FETCHING',
areFetching: bool
}
}
export function wordsHasErrored(bool) {
return {
type: 'WORDS_HAS_ERRORED',
hasErrored: bool
};
}
export function wordsFetchData(parsed) {
return (dispatch) => {
dispatch(wordsAreFetching(true));
fetch('URL', {
method: "POST",
headers: {
"Content-type": "application/json"
},body: JSON.stringify({
words: parsed
})
})
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(wordsAreFetching(false));
return response;
})
.then((response) => response.json())
.then((items) => dispatch(wordsFetchDataSuccess(items)))
.catch(() => dispatch(wordsHasErrored(true)));
};
}
这是我的减速器:
export function word(state = [], action) {
switch (action.type) {
case 'WORDS_FETCH_DATA_SUCCESS':
return action.items;
default:
return state;
}
}
export function wordsAreFetching(state = false, action) {
switch (action.type) {
case 'WORDS_ARE_FETCHING':
return action.areFetching;
default:
return state;
}
}
export function wordsFetchHasErrored(state = false, action) {
switch (action.type) {
case 'WORDS_HAS_ERRORED':
return action.hasErrored;
default:
return state;
}
}
这是我的 componentDidMount 函数:
This is my componentDidMount function:
componentDidMount = (state) => {
this.props.fetchData(state);
};
这是终止后应该调用哪个动作的函数:
This is the function after terminating which the action should be called:
parseInput = async () => {
console.log(this.state.textInput);
let tempArray = this.state.textInput.split(" "); // `convert
string into array`
let newArray = tempArray.filter(word => word.endsWith("*"));
let filterArray = newArray.map(word => word.replace('*', ''));
await this.setState({filterArray: filterArray});
await this.props.updateData(this.state.filterArray);
if (this.state.projectID === "" && this.state.entity === "")
this.dialog.current.handleClickOpen();
else
if (this.state.filterArray.length !== 0)
this.componentDidMount(this.state.filterArray);
};
这些是 mapStateToProps 和 mapDispatchToProps 函数.
These are the mapStateToProps and mapDispatchToProps functions.
const mapStateToProps = (state) => {
return {
items: state.items,
hasErrored: state.wordsFetchHasErrored,
areFetching: state.wordsAreFetching
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: wordsFetchData
};
};
推荐答案
执行抓取只需要一个动作(即WORDS_ARE_FETCHING
),其他情况(即WORDS_HAS_ERRORED
)code> & WORDS_FETCH_DATA_SUCCESS
) 可以在你的 reducer 中处理.
You only need one action for executing fetching (i.e WORDS_ARE_FETCHING
), the rest of the cases (i.e WORDS_HAS_ERRORED
& WORDS_FETCH_DATA_SUCCESS
) can be handled inside your reducer.
您的操作:
export function wordsAreFetching(){
return{
type: 'WORDS_ARE_FETCHING',
}
}
你的新减速器:
export function word(state = [], action) {
switch (action.type) {
case 'WORDS_ARE_FETCHING':
return {...state, error: false, areFetching: true};
case 'WORDS_FETCH_DATA_SUCCESS':
return {...state, items: action.payload , areFetching: false};
case 'WORDS_HAS_ERRORED':
return {...state, error: true, areFetching: false};
default:
return state;
}
然后你可以在你从这里获取数据后触发WORDS_FETCH_DATA_SUCCESS
:
Then you can trigger WORDS_FETCH_DATA_SUCCESS
after you get the data from here:
export function wordsFetchData() {
try {
const response = await axios.get(YOUR_URL);
return dispatch({ type: WORDS_FETCH_DATA_SUCCESS, payload: response.data });
} catch (err) {
return dispatch({ type: WORDS_HAS_ERRORED });
}
}
看看这个示例,它使用了可以帮助您进行异步调用的 axios.
Take a look at this example, it uses axios that can help you with async calls.
这篇关于如何在 redux 中使用 API 调用操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!