react native 整合redux从一个简单的helloworld程序写起

添加依赖

    "react-navigation": "^4.4.4",
    "react-navigation-redux-helpers": "^4.0.1",
    "react-redux": "^7.2.4",
    "redux": "^4.1.0",
    "redux-thunk": "^2.3.0"

创建两个简单的reducers文件,一个返回hello,一个返回world:
/src/reducers/hello/index.js

const initialState = {
	word1:"hello",
}

export default (state = initialState, action)=> {
            return state;
}

/src/reducers/init/index.js

const initialState = {
        word2:" world!",
}

export default (state = initialState, action)=> {
            return state;
}

创建根reducer文件整合上面的两个reducer

import { combineReducers } from "redux";
import hello from "./hello"
import init from "./init"
const rootReducer = combineReducers({
    app: combineReducers({
        hello,
        init
    }),
  
})


export default rootReducer;

创建数据仓库store文件,引入根reducer:

'use strict';
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers'
import {
    createReactNavigationReduxMiddleware,
} from 'react-navigation-redux-helpers';

const middleware = createReactNavigationReduxMiddleware(
    "root",
    state => state.nav,
)

const createStoreWithMiddleware = applyMiddleware(thunkMiddleware, middleware)(createStore);

const initialState = {

}

export default createStoreWithMiddleware(rootReducer, initialState);

入口文件代码如下,注入数据仓库store:

import React, { Component } from 'react';
import App from "./containers/index";
import { Provider } from "react-redux";
import store from "./store/index";

export default class Index extends Component {
    render() {
        return <Provider store={store}>
            <App />
        </Provider>;
    }
}

根组件代码如下:

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


class App extends Component {
    	componentDidMount() {
   		console.log("##########"); 
	}
	render() {
		const { word1,word2 } = this.props;
  		return (
   			<View>
    				<Text>{word1}{word2}</Text>
   			</View>
  		);
	};
}
const mapStateToProps = store => {
    const {
        hello:{word1},
        init:{word2}
    } = store.app
    return {
        word1,
        word2
    };
};

export default connect(mapStateToProps)(App);

页面输出
hello world!

这个例子展示了一个两个state是如何从reducer中展示到页面的具体过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

reg183

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

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

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

打赏作者

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

抵扣说明:

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

余额充值