【问题标题】:Redux when to update state before or after async operation?Redux 何时在异步操作之前或之后更新状态?
【发布时间】:2017-04-20 12:15:14
【问题描述】:

我正在处理一个分页和排序的表。我的初始分页状态是这样的

pagination: {
  sort: 'id',
  order: 'asc',
  page: 1,
  limit: 10
}

当用户单击页码或下一个/上一个按钮时,我会发送一个操作来更改 page,然后我会立即发送操作以从服务器获取数据。这很好用,但如果发生服务器错误我该怎么办。我有两个解决方案

1) 在错误调度 API_ERROR 时将分页回滚到之前的状态

2) 仅在成功后更新分页状态,因此在我收到响应后的 thunk 中,我调度了 updatePagination 操作。

我当前的页面点击处理程序是这样的

onPageChange (page) {
  // Dispatch action to change page state
  this.props.changePage(page)

  // Dispatch action to fetch from server
  this.props.fetchSomePaginatedResponse()
}

然后 thunk fetchSomePaginatedResponse 从状态中获取分页对象以构建 URI 字符串。

我还可以在 thunk 成功时发送 changePage 操作。哪种方法更好,为什么?

【问题讨论】:

    标签: reactjs pagination redux


    【解决方案1】:

    我使用的模式是

    class Pagination extends Component {
        ...
        onPageChange = ( event, page ) => {
            event.preventDefault();
            this.props.setCurrentPage( page );
        };
        render() {
            ...
            return pages.map( ( page, key ) => {
                return <a
                           key={ key }
                           href={ generatePageUrl( page ) }
                           onClick={ event => this.onPageChange( event, page ) }>
                           { page }
                       </a>
            }
            ...
        }
        ...
    }
    
    export default connect(
        ( state ) => ( {
            currentPage: getCurrentPage( state ),
        } ),
        { setCurrentPage }
    )( Pagination );
    

    setCurrentPage 是一个 react redux thunk 并调度两个动作

    setCurrentPage( dispatch, page ) {
        return ( dispatch ) => {
            dispatch( { type: API_PAGE_FETCH } ); // Maybe set isFetching: true in your state tree
    
            // asyncApiRequest should return a promise
            asyncApiRequest( `http://api.example.com/get-page?page=${ page }` )
                .then( data => dispatch( { type: API_PAGE_RECEIVE, data, page } ) )
                .catch( error => dispatch( { type: API_PAGE_ERROR, error } ) );
        }
    }
    

    这种模式效果很好,因为您只需要担心更改组件中的页面,而无需担心处理网络错误等其他事情

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2023-03-31
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      相关资源
      最近更新 更多