我是redux的新手,我正在尝试使其与我的应用程序一起使用,但是在理解如何在其中使用异步操作时遇到了问题。我的动作是api调用。我的其他状态不为空时,应立即调用此操作。我没有遇到任何错误,但是由于数据为空,所以我不认为我的操作被调用了。有人可以帮助您了解我在做什么吗?
这是我的actions.js。单词FetchData是我需要调用的动作:
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函数:
componentDidMount = (state) => {
this.props.fetchData(state);
};
这是终止操作后应调用的函数:
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函数。
const mapStateToProps = (state) => {
return {
items: state.items,
hasErrored: state.wordsFetchHasErrored,
areFetching: state.wordsAreFetching
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: wordsFetchData
};
};
答案 0 :(得分:0)
您只需执行一项操作即可执行抓取操作(即WORDS_ARE_FETCHING
),其余的情况(即WORDS_HAS_ERRORED
和WORDS_FETCH_DATA_SUCCESS
)都可以在化简器中处理。
您的操作
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
:
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 });
}
}
看看这个example,它使用axios可以帮助您进行异步调用。
答案 1 :(得分:0)
几件事:
无需将状态传递到您的componentDidMount
,您的mapDispatchToProps
并未使用它。
这里建议构造这些功能。它们更加简洁易读。
const mapStateToProps = ({items, wordsAreFetching, wordsFetchHasError}) => ({
items,
hasErrored: wordsFetchHasErrored,
areFetching: wordsAreFetching,
});
const mapDispatchToProps = () => ({
fetchData: wordsFetchData(),
});
其他说明和有用的内容: 如果您正在使用thunk,则可以在此处作为第二个参数访问整个redux存储。例如:
return (dispatch, getState) => {
dispatch(wordsAreFetching(true));
console.log('getState', getState());
const { words } = getState().items;
// This is a great place to do some checks to see if you _need_ to fetch any data!
// Maybe you already have it in your state?
if (!words.length) {
fetch('URL', {
method: "POST",
headers: {
......
}
})
我希望这对您有帮助,如果您有其他需要的话。