Redux

1 React Components -> Action Creators -> Reducers -> Store

用户通过界面组件触发action函数,然后通过reducer更新store里存储的数据。

2 redux是单独的框架,不是react的一部分,可以用react-redux中的connect将react与redux关联起来。

 

下面来看下实现的步骤吧~

一、首先看reducers.js吧,他主要更新redux里的数据:

import { combineReducers } from 'redux';
//设置一个初始数据的对象
let initRedux = {
    type: 'A'
};

export default function MathReducer(state = initRedux, action) {
    switch (action.type) {
        case 'change':
            //更新store里的数据
            return {
                ...state,
                type: action.type
            };
        default:
            return state;
    }
}

二、store.js 生成store对象(redux的核心)

import { createStore,applyMiddleware } from 'redux';
import Reducer from './reducers'; // 这里引用的是上一段代码里的内容
import thunk from 'redux-thunk';

//内部会第一次调用reducer函数,得到初始state 
const store = createStore(Reducer, applyMiddleware(thunk)); 

export default store
// 输出的store对象传到组件里,我们可以通过组件的props触发他的dispatch改变redux数据,也可以通过组件的props获取redux数据

三、App.js,这是我们整个程序的入口

import React from 'react';
//你可以把Provider想象成一个注入器,它可以帮我们把store注入到我们的根组件上,这样的话store将无处不在
import { Provider } from 'react-redux'; 
import store from './redux/store'; // 这里的store指上一段代码里的内容
import Main from './Main';

export default class App extends React.PureComponent {
  render() {
    return (
      <Provider store={store}> // 在这里把store注入到它包裹的组件里
        <Main/>
      </Provider>
    );
  }
}

四、Main.js,在这里我们可以通过组件的props触发他的dispatch改变redux数据,也可以通过组件的props获取redux数据,但是需要用connect把Main组件和store连接起来

import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import Content from './Content';
import { styles } from './style/styles';

class Main extends Component{
    constructor(props){
        super(props);
    }
    render() {
        return (
            <View>
                <View style={styles.stCommon.wrap}>
                    <TouchableOpacity onPress={() => {this.changeType('A')}}>
                        <Text style={styles.stCommon.red}></Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => {this.changeType('B')}}>
                        <Text style={styles.stCommon.blue}></Text>
                    </TouchableOpacity>
                </View>
                // 把store传给子组件Content
                <Content store={this.props}/>
            </View>
        )
    }   
    changeType (type){
         this.props.dispatch({
            type: 'change',
            type: type
        });
    }
}

let select = (state) => {
    return {
        type: state.type
    }
}
export default connect(select)(Main);

 

posted @ 2019-07-05 17:47  seeBetter  阅读(238)  评论(0编辑  收藏  举报