微信公众号首发
本教程总共5篇,每日更新一篇,请关注我们!你可以进入历史消息查看以往文章,也敬请期待我们的新文章!
1、React第三方组件3(状态管理之Flux的使用①简单使用)---2018.03.06
2、React第三方组件3(状态管理之Flux的使用②TodoList上)---2018.03.07
3、React第三方组件3(状态管理之Flux的使用③TodoList中)---2018.03.08
4、React第三方组件3(状态管理之Flux的使用④TodoList下)---2018.03.09
5、React第三方组件3(状态管理之Flux的使用⑤异步操作)---2018.03.12
开发环境:Windows 8,node v8.9.1,npm 5.5.1,WebStorm 2017.2.2
今天我们用Flux写下TodoList
1、在flux下新建flux2文件夹,并建立Index.jsx
import Main from './Main';
import {Container} from 'flux/utils';
import TodoActions from './TodoActions';
import TodoStore from './TodoStore';
function getStores() {
return [
TodoStore
];
}
function getState() {
return {
state: TodoStore.getState(),
addTodo: TodoActions.addTodo,
};
}
export default Container.createFunctional(Main, getStores, getState);
2、建立Main.jsx
import React from 'react';
class Input extends React.Component {
render() {
let {addTodo} = this.props;
return (className="todoList">
type="text" ref="todoInput"/>
);
}
}
class List extends React.Component {
render() {
let {list} = this.props.state;
return (
{
list.length > 0 && list.map(data =>key={data.id}>
{data.title}
)
}
);
}
}
const Index = (props) =>className="todoList">
{...props}/>
{...props}/>
;
export default Index;
3、建立TodoActions.js
import TodoActionTypes from './TodoActionTypes';
import TodoDispatcher from './TodoDispatcher';
const Actions = {
addTodo(text) {
TodoDispatcher.dispatch({
type: TodoActionTypes.ADD_TODO,
text,
});
}
};
export default Actions;
4、建立TodoActionTypes.js
import TodoActionTypes from './TodoActionTypes';
import TodoDispatcher from './TodoDispatcher';
const Actions = {
addTodo(text) {
TodoDispatcher.dispatch({
type: TodoActionTypes.ADD_TODO,
text,
});
}
};
export default Actions;
5、建立TodoDispatcher.js
import {Dispatcher} from 'flux';
export default new Dispatcher();
6、建立TodoStore.js
import {ReduceStore} from 'flux/utils';
import TodoActionTypes from './TodoActionTypes';
import TodoDispatcher from './TodoDispatcher';
class TodoEditStore extends ReduceStore {
constructor() {
super(TodoDispatcher);
}
getInitialState() {
return {list: []};
}
reduce(state, action) {
let list = state.list;
switch (action.type) {
case TodoActionTypes.ADD_TODO:
if (!action.text) {
alert('内容不能为空');
return state;
}
list.push({id: state.list.length + 1, title: action.text, status: 1});
return {list};
default:
return state;
}
}
}
export default new TodoEditStore();
7、修改flux下Index.jsx
import React from 'react';
import {HashRouter, Route, NavLink, Redirect} from 'react-router-dom';
import Flux1 from './flux1/Index'
import Flux2 from './flux2/Index'
const Index = ({match}) =>
className="nav">
to="/Flux/Flux1" activeClassName="selected">Flux1
to="/Flux/Flux2" activeClassName="selected">Flux2
exact path={`${match.url}`}
render={() => (to={`${match.url}/Flux1`}/>)}/>
path={`${match.url}/Flux1`} component={Flux1}/>
path={`${match.url}/Flux2`} component={Flux2}/>
;
export default Index;
8、查看浏览器
本文完
禁止擅自转载,如需转载请在公众号中留言联系我们!
感谢童鞋们支持!
如果你有什么问题,可以在下方留言给我们!