react-redux使用

1、安装依赖:react-redux,命令:npm install react-redux

2、安装依赖:redux-thunk,命令:npm install redux-thunk

3、定义action的type类型,文件名称假设命名为types.ts,内容如下:

export default {
    DATA_LOADING:'DATA_LOADING',
    DATA_LOAD_SUCCESS:'DATA_LOAD_SUCCESS',
    DATA_LOAD_FAIL:'DATA_LOAD_FAIL'
}

4、定义返回action的函数,文件名称假设命名为studentAction.ts,内容如下:

import Types from 'types';

export default function onLoadStudentData(url:string){
    return (dispatch)=>{
        dispatch({type:Types.DATA_LOADING});
        fetch(url).then(res=>{
            dispatch({type:Types.DATA_LOAD_SUCCESS,list:res.list});
        }).catch(error=>{
            console.log(error);
            dispatch({type:Types.DATA_LOAD_FAIL});
        });
    }
}

5、定义reducer,文件名称假设命名为studentReducer.ts,内容如下:

import Types from 'types';

const defaultState={}

export default function(state:defaultState,action){
    switch (action.type) {
    case Types.DATA_LOAD_SUCCESS:
      const result = {
        ...state,
        list:action.list,
        isLoading: false,
      };
      return result;
    case Types.DATA_LOADING:
      const result1 = {
        ...state,
        isLoading: true,
      };
      return result1;
    case Types.DATA_LOAD_FAIL:
      const result2 = {
        ...state,
        isLoading: false,
      };
      return result2;
    default:
      return state;
  }
}

6、定义combineReducers,文件名称假设命名为combineReducers.ts,内容如下:

import { combineReducers } from "redux";
import studentReducer from "./studentReducer";

const index = combineReducers({
  student: studentReducer //注意,这个名字一定要准确
});

export default index;

7、定义store,文件名称假设命名为studentStore.ts,内容如下:

import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import reducers from "studentReducer";

const middlewares = [thunk];

export default createStore(reducers, applyMiddleware(...middlewares));

8、在类组件中使用,内容如下:

import React, { Component } from "react";
import { FlatList, Button, StyleSheet, Text, View, RefreshControl } from "react-native";
import { connect } from "react-redux";
import onLoadStudentData from '../studentAction';


class StudentList extends Component<any> {

  constructor(props: any) {
    super(props);
  }

  componentDidMount() {
    const { onLoadStudentData } = this.props;
    const url = this.genFetchUrl();
    onLoadStudentData(url);
  }

  loadData() {
    const { onLoadStudentData } = this.props;
    const url = this.genFetchUrl();
    onLoadStudentData(url);
  }

  genFetchUrl(key: string) {
    return "http://test.cos.com/student/list";
  }

  renderItem(data: any) {
    const item = data.item;
    return <View style={{ marginBottom: 10 }}>
      <Text style={{ backgroundColor: "#faa" }}>
        {JSON.stringify(item)}
      </Text>
    </View>
  }

  render() {
    const { student} = this.student;
    let store = {
      items: [],
      isLoading: false
    }
    if (student) {
      store =  {
          items: student.list,
          isLoading: false
      }
    }

    return (
      <View style={styles.container}>
        <FlatList
          data={store.items}
          renderItem={
            data => this.renderItem(data)
          }
          keyExtractor={(item: any) => "" + item.id}
          refreshControl={
            <RefreshControl
              title={'Loading'}
              titleColor={THEME_COLOR}
              colors={[THEME_COLOR]}
              refreshing={store.isLoading}
              onRefresh={() => {
                this.loadData()
              }}
              tintColor={THEME_COLOR}
            />
          }
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  }
});

const mapStateToProps = (state: any) => {
  return {
    student: state.student
  }
};

const mapDispatchToProps = (dispatch: any) => ({
  onLoadStudentData: (url: string) => dispatch(onLoadStudentData(url))
});

const StudentListPage = connect(mapStateToProps, mapDispatchToProps)(StudentList);

export default StudentListPage;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值