标签:asics 一般来说 nbsp nec sharp operator ken patch org
Redux 是 JavaScript 状态容器,提供可预测化的状态管理。
安装: npm install --save redux
安装React绑定库和开发者工具:npm install --save react-redux;npm install --save-dev redux-devtools
Redux 三大原则单一数据源:整个应用的state被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个store 中。State只读:惟一改变 state 的方法就是触发 action,action 是一个用于描述已发生事件的普通对象。
使用纯函数来执行修改:通过编写reducers实现,reducer只是一些纯函数,接收state和action,返回新的state。
Action
Action 是把数据从应用(译者注:这里之所以不叫 view 是因为这些数据有可能是服务器响应,用户输入或其它非 view 的数据 )传到 store 的有效载荷。它是 store 数据的唯一来源。一般来说你会通过 store.dispatch() 将 action 传到 store。
1 export const ADD_ITEM = ‘ADD_ITEM‘; 2 export function addItem(text) { 3 return {type: ADD_ITEM, text} 4 }
Reducer
在 Redux 应用中,所有的 state 都被保存在一个单一对象中,Reducer就是用来更新state
import {combineReducers} from ‘redux‘
import {ADD_ITEM, DELETE_ITEM, CHANGE_VALUE,GET_VALUE} from ‘./actions‘
function todos(state = [], action) {
switch (action.type) {
case ADD_ITEM:
return [
...state, {
text: action.text,
completed: false
}
]
case DELETE_ITEM:
state.slice(action.index);
return state;
default:
return state
}
}
Store
Store 就是把它们联系到一起的对象。Store 有以下职责:
getState() 方法获取 state;dispatch(action) 方法更新 state;subscribe(listener) 注册监听器;subscribe(listener) 返回的函数注销监听器。再次强调一下 Redux 应用只有一个单一的 store。当需要拆分数据处理逻辑时,你应该使用 reducer 组合 而不是创建多个 store。
const operationApp = combineReducers({todos, value})
export default operationApp;
使用
index.js中
let store = createStore(todoApp)
let rootElement = document.getElementById(‘root‘)
render(
<Provider store={store}>
<ToDo />
</Provider>,
rootElement
)
Todo.Js中
const { dispatch,todos,value,store} = this.props;
return (
<div>
<MuiThemeProvider>
<Paper style={style} zDepth={3}>
<div className="todo-wrap">
<div style={divstyle}>
<TodoHeader
className="todoHeader"
addTodo={text=>dispatch(addItem(text))}
curValue={value}
valueChange={text=>dispatch(valueChange(text))}/>
</div>
</div>
</Paper>
</MuiThemeProvider>
</div>
);
}
function select(state) {
return {
todos: state.todos,
value: state.value
}
}
export default connect(select)(ToDoApp);
以上例子是结合react的简单实现。http://www.redux.org.cn/docs/react-redux/quick-start.html
待续
标签:asics 一般来说 nbsp nec sharp operator ken patch org
原文地址:http://www.cnblogs.com/yxcoding/p/7071385.html