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

2021/6/27 11:14:22

本文主要是介绍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中展示到页面的具体过程。



这篇关于react native 整合redux从一个简单的helloworld程序写起的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程