使用 react native 和 redux 进行异步调用,thunk

sbkl

我一直在按照本教程将 redux 集成到我的 React Native 应用程序中。

https://github.com/jlebensold/peckish

在我的主页视图中,我无法从我的操作文件夹中调用函数。

一个区别是我在我的应用程序中使用了 react-navigation。想知道我是否需要将 redux 与 react 导航集成才能对所有数据使用 redux?

下面是我一直在做的完整实现代码。

在主屏幕上,我调用 ComponentDidMount 上的 fetchSite 函数以启动与 axios 的异步调用。但是我什至无法访问此功能。

很抱歉这篇长文章,但我无法弄清楚如何使这项工作如此难以制作更短的代码示例来解释我的应用程序的结构。

如果有任何问题,请告诉我。

index.ios.js

import React from 'react'
import { AppRegistry } from 'react-native'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose} from 'redux'
import thunkMiddleware from 'redux-thunk'
import { createLogger } from 'redux-logger'

import reducer from './app/reducers'
import AppContainer from './app/index'


// middleware that logs actions
const loggerMiddleware = createLogger({ predicate: (getState, action) => __DEV__  });

function configureStore(initialState) {
    const enhancer = compose(
        applyMiddleware(
            thunkMiddleware, // lets us dispatch() functions
            loggerMiddleware,
        ),
    );
    return createStore(reducer, initialState, enhancer);
}

const store = configureStore({});

const App = () => (
    <Provider store={store}>
        <AppContainer />
    </Provider>
);

AppRegistry.registerComponent('Appero', () => App;

减速器/ index.js

import { combineReducers } from 'redux';
import * as sitesReducer from './sites'

export default combineReducers(Object.assign(
    sitesReducer,
));

减速器/sites.js

import createReducer from '../lib/createReducer'
import * as types from '../actions/types'

export const searchedSites = createReducer({}, {
    [types.SET_SEARCHED_SITES](state, action) {
        let newState = {};
        action.sites.forEach( (site) => {
            let id = site.id;
            newState[id] = Object.assign({}, site, { id });
        });
        return newState;
    },

});

../lib/createReducer

export default function createReducer(initialState, handlers) {

    return function reducer(state = initialState, action) {
        if (handlers.hasOwnProperty(action.type)) {

            return handlers[action.type](state, action)
        } else {
            return state
        }
    }
}

../动作/类型

export const SET_SEARCHED_SITES = 'SET_SEARCHED_SITES';

./app/index 中的 AppContainer

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { ActionCreators } from './actions';

console.log(ActionCreators); //Properly gathered the functions from the actions folder

import { Root } from './config/router';

window.store = require('react-native-simple-store');
window.axios = require('axios');

class App extends Component {
    render() {
        return (
            <Root />
        )
    }
}

function mapDispatchToProps(dispatch) {

    return bindActionCreators(ActionCreators, dispatch);
}

export default connect(mapDispatchToProps)(App);

'./actions' 中的 ActionCreators;

import * as SiteActions from './sites'

export const ActionCreators = Object.assign({},
    SiteActions,
);

'./actions/sites' 中的操作

import * as types from './types' //See above

export function fetchSites(token) {

    return (dispatch, getState) => {

        let instance = axios.create({
            baseURL: url + 'api/',
            timeout: 10000,
            headers: {'Accept' : 'application/json', 'Authorization' : 'Bearer ' + token}
        });

        instance.get('/sites?page=1')
            .then(response => {

                console.log(response.data.data);

                dispatch(setSearchedSites({sites: response.data.data}));

            }).catch(error => {

                console.log(error);
        });

    }
}

export function setSearchedSites({ sites }) {

    return {
        type: types.SET_SEARCHED_SITES,
        sites,
    }
}

基于 react-navigation 的导航根文件我在这个例子中尽可能简单。

import React from 'react';

import {StackNavigator} from 'react-navigation';

import Home from '../screens/Home';

export const Root = StackNavigator({
    Home: {
        screen: Home,
    }
});

最后是我的主屏幕

import React, {Component} from 'react';
import { connect } from 'react-redux';
import {Text, View} from 'react-native';

class Home extends Component {

    componentDidMount()
    {
        let token = "12345678" //Just for this example
        this.props.fetchSites(token).then( (response) => {
            console.log(response);
        });
    }

    render() {

        return (
            <View>
                <Text>This is the Home view</text>
            </View>
        );
    }
}

function mapStateToProps(state) {
    return {
        searchedSites: state.searchedSites
    };
}

export default connect(mapStateToProps)(Home);
基尚·瓦盖拉

要使用操作方法,您需要像这样在主屏幕中连接

import { fetchSites } from '<your-path>'

// your Home's other code.

const mapDispatchToProps = (dispatch) => {
    return{
        fetchSites:dispatch(fetchSites())
    } 
}

export default connect(mapStateToProps,mapDispatchToProps)(Home);

之后,您可以随时将fetchSites用作this.props.fetchSites

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用Redux Thunk在React Redux应用程序中保持异步调用的DRY

如何在带有thunk的react-redux挂钩中进行异步调用?

Redux-thunk 异步调用和状态

在异步调用axios API之后使用带有React Hook和Redux的SetState

使用React Native,Redux和Navigator进行导航的正确方法

使用React-Native和mapStateToProps的Redux

在 Redux 的 Action 中,使用回调调用函数(使用 async/await 和 React-Native-Contacts)

使用React和Redux进行异步图像加载

使用React Native和Redux的动画状态管理

React 和 redux 使用异步数据获取

React-native和Redux健康方式调用道具更改

React Actions 使用 RxJS 进行并行异步调用

使用React.useMemo进行异步调用

如何使用AngularJs和Typescript进行异步调用

如何使用Express和Node进行异步调用

在React-Native应用中,如何使用SwitchNavigator(react-navigator)和react-redux?

使用React,Jest,Redux和Thunk进行测试中的无限循环

使用自定义异步中间件进行分派 - Redux Thunk - react Router

React native、redux 和 axios:UnhandledPromiseRejectionWarning

React-native 和 redux 操作

使用 redux thunk 进行异步 api 获取

使用React-Navigation和Redux的React Native-如何实现全局可用的“注销”按钮

如何使用 Redux Thunk 和 Redux Toolkit 进行发布请求

使用React,Redux和Axios处理异步请求?

在 react native 中使用 Redux 和本地状态以优化性能的最佳方式?

如何使用搜索栏和Redux Hooks在React Native中搜索FlatList

使用React-Native和Redux在Actions中访问导航器

使用 Redux 和 React Native 将值传递给动作创建者

如何将 Cloud Firestore 与 React Native 和 Redux 结合使用?