在React Native中将ScrollView中的Pull-To-Refresh与Redux集成

时间:2018-10-13 10:41:41

标签: react-native redux react-redux pull-to-refresh

我正在尝试使用<ScrollView>refreshControl添加拉动刷新功能,并将其与Redux集成。

来自https://facebook.github.io/react-native/docs/refreshcontrol的示例:

_onRefresh = () => {
    this.setState({refreshing: true});
    fetchData().then(() => {
      this.setState({refreshing: false});
    });
}

我的问题是我自己的fetchData函数为减速器调度了要处理的动作,据我所知,这不是一个可以实现的承诺。因此,在这种情况下,我不太了解与Redux的集成。如上例所示,我需要在代码中进行哪些更改才能将refreshing设置为false?


PostFeedScreen.js

// on mount, fetch all posts from the API
componentDidMount() {
    this.props.fetchPostsFromAPI();
}

_onRefresh = () => {
    this.setState( { refreshing: true } );
    this.props.fetchPostsFromAPI().then( () => { // error
        this.setState( { refreshing: false } );
    });
}

// map dispatch to props
const mapDispatchToProps = ( dispatch ) => {
    return {
        fetchPostsFromAPI: () => {
            dispatch( fetchPostsFromAPI() );
        }
    }
}

PostActions.js

// fetch all posts
export function fetchPostsFromAPI() {
    return( dispatch ) => {
        let loadData = new Promise( ( resolve, reject ) => {
            resolve( postsInitial ); // using dummy data for now
        })
        loadData
            .then( posts => dispatch( fetchPostsSuccess( posts ) ) );
}

// is used if posts were succesfully loaded
function fetchPostsSuccess( posts ) {  
    return {
        type: PostConstants.FETCH_POSTS_SUCCESS,
        data: posts,
    }
}

PostReducer.js

const PostReducer = ( state = initialState, action ) => {

    switch( action.type ) {

        // if fetching data was successful
        case PostConstants.FETCH_POSTS_SUCCESS: {
            return {
                ...state,
                posts: action.data,
            }
        }

        default: {
            return state
        }
}

1 个答案:

答案 0 :(得分:1)

您收到一个错误,原因是您致电.then,然后调用了一些不返回promise的内容。只需在loadData前面添加return,因为您可以链接promise。

export function fetchPostsFromAPI() {
  return dispatch => {
    let loadData = new Promise((resolve, reject) => {
      resolve(postsInitial);
    });

    return loadData.then(posts => dispatch(fetchPostsSuccess(posts)))
  };
}