# 安装
yarn add redux
yarn add react-redux
yarn add redux-logger
# 集成
# 创建 Action
Action 是把数据从应用(译者注:这里之所以不叫 view 是因为这些数据有可能是服务器响应,用户输入或其它非 view 的数据 )传到 store 的有效载荷。它是 store 数据的唯一来源。一般来说你会通过 store.dispatch() 将 action 传到 store
在
react-native根目录下创建目录src/redux/actions创建对应页面的
action文件目录及文件├── src | └── redux | └── actions | |── homeAction | | └── actionType.js | | └── index.js | └── myAction | └── actionType.js | └── index.js └──
这里把不同的 action 分开是为了后期更好的维护,后期页面太多,出现问题,只需要找到对应的 action 解决就可以
了
在 actionType 中定义要执行的动作, 能让人看见就明白当前要执行的是什么
//homeAction -> actionType.js
export const ADD_TODO = 'ADD_TODO'; //增加元素
export const GET_LIST = 'GET_LIST'; //获取列表
export const DEL_TODO = 'DEL_TODO'; //删除元素
//homeAction -> index
import { ADD_TODO, GET_LIST, DEL_TODO } from './actionType'
/* action 创建函数 */
export function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
export function getList() {
return {
type: GET_LIST
}
}
export function delTodo(text) {
return {
type: DEL_TODO,
text
}
}
# 创建Reducer
Reducers 指定了应用状态的变化如何响应 actions 并发送到 store 的,记住 actions 只是描述了有事情发生了这一事实,并没有描述应用如何更新 state
在
react-native根目录下创建目录src/redux/reducers创建对应页面的
reducer文件目录及文件├── src └── redux └── actions | |── homeAction | | └── actionType.js | | └── index.js | └── myAction | └── actionType.js | └── index.js └── reducers |── homeReducer | └── index.js └── myReducer | └── index.js └── index.js
# 创建Store
使用 action 来描述“发生了什么”,和使用 reducers 来根据 action 更新 state 的用法。
Store 就是把它们联系到一起的对象
在
react-native根目录下创建目录src/redux/store创建
store文件├── src └── redux └── actions | |── homeAction | | └── actionType.js | | └── index.js | └── myAction | └── actionType.js | └── index.js └── reducers | |── homeReducer | | └── index.js | └── myReducer | | └── index.js | └── index.js └── store └── index.js
// index.js
import { applyMiddleware, createStore } from 'redux'
import logger from 'redux-logger'
import rootReducer from '../reducer/index'
let store = createStore(
rootReducer,
applyMiddleware(logger)
)
export default store;