React Native Redux 用法介绍

React Native Redux 用法介绍

简介

简单来说,redux 就是统一帮我们管理了 react 组件的 state 状态。redux适用于多交互,多数据源,复杂程度高的工程中。也就是当你感觉state状态已经复杂到没办法维护的时候,可以考虑redux。

工作原理图:

  • Action:它的作用就是将我们更新组件的状态 ( state ) 的每个动作抽象为一个行为,它有一个必须的参数 type,定义了 Action(行为) 的名称,其他参数可自定义。
  • Reducer:根据传入的 Action行为和旧的 state 对象,返回一个新的 state
  • Store:当 reducer 返回了新的 state 后,这个 state 怎么传到组件和存储就成了问题,redux 就是把这个状态统一放到 store 中进行管理。

示例

下面是一个点击后字体放大的示例,效果如下:

1)目录结构

2)代码实现

// ../actions/index.js


'use strict';
export const BIGGER_TEXT = 'BIGGER_TEXT'
export function bigger (fontSize) {
    return (dispatch) => {
        dispatch({type: BIGGER_TEXT, fontSize: fontSize})
    }
}

// ../reducers/index.js


'use strict';

import { combineReducers } from 'redux';

import {BIGGER_TEXT} from "../actions/" //Import the actions types constant we defined in our actions

let dataState = { fontSize:15, };

const dataReducer = (state = dataState, action) => {
    switch (action.type) {
        case BIGGER_TEXT:
            state = Object.assign({}, state, {fontSize:action.fontSize})
            return state;
        default:
            return state;
    }
};


// Combine all the reducers
const rootReducer = combineReducers({
    dataReducer
})

export default rootReducer;

// store.js


'use strict';

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import reducers from '../app/reducers/index'; //Import the reducer

// Connect our store to the reducers
export default createStore(reducers, applyMiddleware(thunk));

// setup.js

'use strict';

import React, { Component } from 'react';
import { Provider } from 'react-redux';

import store from '../app/store'; //Import the store
import Main from '../app/index' //Import the app/index.js file
import TestFont from './components/test_font' //Import the app/index.js file


function setup() {
    class Root extends Component {
        render() {
            return (
                <Provider store={store}>
                    <TestFont/>
                </Provider>
            );
        }
    }

    return Root;
}

module.exports = setup;

// index.android.js

import { AppRegistry } from 'react-native';
import setup from './app/setup';

AppRegistry.registerComponent('TestApp', () => setup());

// ../components/test_font.js

'use strict';

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

var {StyleSheet, View, Platform, Dimensions, Text, TouchableOpacity,} = require('react-native');


class TestFont extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <View style={{flex: 1, backgroundColor: '#fff', alignItems:'center', justifyContent:'center'}}>
                <TouchableOpacity onPress={this.bigger.bind(this)}>
                    <Text style={{fontSize:this.props.fontSize}}>Click Me</Text>
                </TouchableOpacity>
            </View>
        );
    }

    bigger() {
        let fontSize = this.props.fontSize + 5;
        this.props.bigger(fontSize)
    }

};

function mapStateToProps(state, props) {
    return {fontSize:state.dataReducer.fontSize,}
}

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

export default connect(mapStateToProps, {bigger})(TestFont);

首先我们在Action中定义function bigger (fontSize)接口和type=BIGGER_TEXT,在test_font.js中通过this.props.bigger(fontSize)触发Action的bigger接口,进而调用store的dispatch将具体行为(BIGGER_TEXT)发到reducers中处理,返回一个全新的state,最后回调mapStateToProps通知TestFont组件更新字体大小;

参考文档:
redux官方文档
React-Native 之 redux 与 react-redux

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
React-Redux是一个用于在React应用程序中管理状态的库。它结合了ReactRedux,使得在React组件中使用Redux变得更加简单。 要使用React-Redux,首先需要安装它: ``` npm install react-redux ``` 然后,在你的应用程序中引入所需的模块: ```jsx import React from 'react'; import { Provider, useDispatch, useSelector } from 'react-redux'; import { createStore } from 'redux'; // 创建一个Redux store const store = createStore(reducer); // 创建一个React组件 const App = () => { // 使用useDispatch和useSelector钩子来访问Redux store const dispatch = useDispatch(); const state = useSelector(state => state); // 渲染组件 return ( <div> <h1>Hello React-Redux!</h1> <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> <p>Count: {state.count}</p> </div> ); }; // 渲染根组件并将Redux store传递给应用程序 ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); ``` 在上面的示例中,我们首先创建了一个Redux store,然后使用`useDispatch`和`useSelector`钩子来访问Redux store。`useDispatch`用于触发action,`useSelector`用于选择需要的state。然后,在组件中,我们可以通过`dispatch`函数来分发action,以更新状态。最后,我们使用`Provider`组件将Redux store传递给整个应用程序。 这只是React-Redux的基本用法,它还提供了更多的功能和API来帮助你更好地管理状态。你可以参考React-Redux的官方文档来了解更多用法和示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chengyuan9160

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值