【JAVASCRIPT】React + Redux
摘要
Redux 数据流图
- View 层由React 控制, 根据state 变化 刷新渲染组件,作用是根据更新的数据重新渲染组件
- Stroe 层其实就是state存储器,作用是更新数据
- Dispatch 层根据action 更新 state, 作用是分发事件
- Action 层绑定action类型和参数,并传递给dispatcher, 作用是通知有事件发生
这样保证预知组件的每个动作,并对每个动作做出相应的更新变化。
实战
html 部分
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>demo</title>
</head>
<body>
<div id="container"></div>
<script type="text/javascript" src="bundle/app.js"></script>
</body>
</html>
app.js
var Redux = require('redux');
var React = require('react');
var ReactDOM = require('react-dom');
// action creator
var addTodoActions = function(text){
return {
type: 'add_todo',
text: text
};
};
// reducers
var todoReducer = function(state, action){
if(typeof state === 'undefined'){
return [];
}
switch(action.type){
case 'add_todo':
return state.slice(0).concat({
text: action.text,
completed: '未完成'
});
break;
default:
return state;
}
};
var store = Redux.createStore(todoReducer);
var App = React.createClass({
getInitialState: function(){
return {
items: store.getState()
};
},
componentDidMount: function(){
var unsubscribe = store.subscribe(this.onChange);
},
onChange: function(){
this.setState({
items: store.getState()
});
},
handleAdd: function(){
var input = ReactDOM.findDOMNode(this.refs.todo);
var value = input.value.trim();
if(value)
store.dispatch(addTodoActions(value));
input.value = '';
},
render: function(){
return (
<div>
<input ref="todo" type="text" placeholder="输入todo项" style={{marginRight:'10px'}} />
<button onClick={this.handleAdd}>点击添加</button>
<ul>
{
this.state.items.map(function(item){
return <li>{item.text} | 完成状态: {item.completed}</li>;
})
}
</ul>
</div>
)
},
});
ReactDOM.render(
<App />,
document.getElementById('container')
);
计划、执行、每天高效的活着学着