代码之家  ›  专栏  ›  技术社区  ›  animaonline

订阅react组件中的redux操作

  •  4
  • animaonline  · 技术社区  · 6 年前

    FETCH_REQUESTED
    FETCH_SUCCEEDED
    FETCH_FAILED
    

    最后,如果成功,则返回实际响应或错误对象。

    FETCH_FAILED 操作并根据错误类型显示错误消息(404/401和其他状态代码)

    export const fetchData = () => {
        return async (dispatch, getState) => {
            const appState = getState();
    
            const { uid } = appState.appReducer;
    
            await dispatch(fetchRequested());
    
            try {
                const response = await LookupApiFactory().fetch({ uid });
    
                dispatch(fetchSucceeded(response));
    
                return response;
            } catch (error) {
                dispatch(fetchFailed());
    
                return error;
            }
        }
    }
    

    3 回复  |  直到 6 年前
        1
  •  4
  •   Rohith Murali    6 年前

    要实现一个正确的redux回调和存储机制,您应该有一个存储来保存所有数据,

    const store = createStore(todos, ['Use Redux'])
    

    然后,将数据发送到存储器,

    store.dispatch({
      type: 'FETCH_FAILED',
      text: reposnse.status //Here you should give the failed response from api
    });
    

    然后,可以使用subscribe函数从任何组件的存储中获取值。它将在调度操作时被调用,并且状态树的某些部分可能已经更改。

    store.subscribe(()=>{
      store.getState().some.deep.property
    })
    

    这是Redux的一个简单实现。随着你的应用程序变得越来越复杂,你需要将你的还原函数拆分成单独的函数,每个函数都使用 combineReducers . 你可以从 redux.js site

        2
  •  0
  •   Yuriy Yakym    6 年前

    connect 函数来自 react-redux 图书馆。这是一个订阅状态更改的HoC。看看这个库,另外它还允许您绑定动作创建者来分派,这使您能够从组件分派动作。

    你可以这样使用它:

    import React from 'react';
    import { connect } from 'react-redux';
    
    const MyComponent = ({ data, error }) => (
      <div>
        {error && (
          <span>Error occured: {error}</span>
        )}
    
        {!error && (
          <pre>{JSON.stringify(data, null, 2)}</pre>
        )}
      </div>
    );
    
    const mapStateToProps = (state) => ({
      data: state.appReducer.data,
      error: state.appReducer.error
    });
    
    export default connect(mapStateToProps)(MyComponent);
    

    const MyComponent = ({ data, error }) => {
      if (error) {
        return (
          <span>Error occured: {error}</span>
        );
      }
    
      return (
        <pre>
          {JSON.stringify(data, null, 2)}
        </pre>
      );
    }
    
        3
  •  0
  •   Brandon Culley    6 年前

    FETCH_FAILED 动作时,可以放一些有意义的标志来表示 有一些失败。基于在该标志上,您可以显示错误消息或执行其他操作。

    const testReducers =(state,actione)=>{
    
        case 'FETCH_FAILED' : {
    
            return {
                ...state,{ error_in_response : true }
            }
        };
    
        default : return state;
    }
    

    combineReducers 用于组合减速器;

    const mapStateToProps=(state)=>{
    
        return {
            error_in_response : state.testReducers.error_in_response
        }
    }
    connect(mapStateToProps)(yourComponent)
    

    在组件中,可以使用 this.props.error_in_response