如何在 redux 中使用 API 调用操作?

IT技术 reactjs redux redux-thunk
2021-05-05 23:55:29

我是 redux 的新手,我试图让它与我的应用程序一起工作,但我在理解如何使用其中的异步操作时遇到了问题。我有 api 调用的操作。一旦我的其他状态不为空,就应该调用此操作。我没有犯任何错误,但我认为我的操作没有被调用,因为数据是空的。任何人都可以帮助理解我做错了什么吗?

这是我的 actions.js。wordsFetchData 是我需要调用的操作:

 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
    };
};
2个回答

你只需要一个动作来执行获取(即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 });
    }
 }

看看这个例子,它使用 axios 可以帮助您进行异步调用。

几件事:

  1. 无需将状态传递到您的componentDidMount,您mapDispatchToProps没有使用它。

  2. 这是构建这些功能的建议。它们更加简洁和可读。

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: {
                ......
      }

    })

我希望这会有所帮助,如果您需要任何其他信息,请随时询问。