添加依赖
"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中展示到页面的具体过程。