【问题标题】:How to work with API call action in redux?如何在 redux 中使用 API 调用操作?
【发布时间】:2019-10-01 06:04:54
【问题描述】:

我是 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
    };
};

【问题讨论】:

  • 你使用过 redux thunk 或 redux saga 之类的中间件吗?
  • 是的,redux-thunk
  • @RajSaraogi 我认为问题在于我说错了

标签: reactjs redux redux-thunk


【解决方案1】:

你只需要一个动作来执行获取(即WORDS_ARE_FETCHING),其余的情况(即WORDS_HAS_ERRORED & WORDS_FETCH_DATA_SUCCESS)可以在你的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

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。

【讨论】:

    【解决方案2】:

    有几点:

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

    希望对您有所帮助,如果您还有其他需要,请随时提出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 2016-02-21
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多