React六——Redux
发布时间:2020-12-15 06:38:36 所属栏目:百科 来源:网络整理
导读:数据流 1.reducer通过给第一个参数默认值来设置初始状态2.view通过store.getState()来获取store里管理的状态3.view层产生用户操作,调用了actionCreator的方法4.在actionCreator的方法中,创建标识性的action通过store.dispatch方法传递给reducer'5.reducer
数据流1.reducer通过给第一个参数默认值来设置初始状态 2.view通过store.getState()来获取store里管理的状态 3.view层产生用户操作,调用了actionCreator的方法 4.在actionCreator的方法中,创建标识性的action通过store.dispatch方法传递给reducer' 5.reducer执行,接收到actionCreator传递过来的action来进行判断' 6.reducer经对action的判断后返回了新的状态 7.store里的状态更新后,store.subscribe方法里的函数执行,view重新获取状态 1、创建store.jsimport {createStore} from 'redux' import reducer from './reducer' const store = createStore(reducer) //Redux 提供createStore这个函数,用来生成 Store。 export default store 2、创建reducer.jsreducer 纯函数 //第一个参数就是默认的store的state let _state = { //1.reducer通过给第一个参数默认值来设置初始状态' todos:[] } let count = 0 //注意,reducer必须return出state,这样store才能用到state const reducer = (state=_state,action)=>{ switch(action.type) //5.reducer执行,接收到actionCreator传递过来的action来进行判断' case 'GET_TODOS': state.todos=state.todos.concat(action.todos) count = state.todos.length console.log(state,111) return state;break; case 'REMOVE_TODO': //6.reducer经对action的判断后返回了新的状态' for(var i =0;i<state.todos.length;i++){ if(state.todos[i].id==action.id){ state.todos.splice(i,1) break; } } return state;break; default : return state;break; } } export default reducer 3、actionCreator.jsimport axios from 'axios' import store from './store' const actionCreator = { getTodos(){ axios.get("./public/json/todos.json").then((res)=>{ store.dispatch({ type:'GET_TODOS',todos:res.data }) }) },removeTodo(id){ //4.在actionCreator的方法中,创建标识性的action通过store.dispatch方法传递给reducer' store.dispatch({ type:'REMOVE_TODO',id }) } } export default actionCreator view层import React from 'react' import TodoItem from './TodoItem' import store from './redux/store' class TodoBox extends React.Component { constructor(props,context){ super(props,context) this.state = { todos:store.getState().todos //2.view通过store.getState()来获取store里管理的状态 } } render(){ let {todos} = this.state return ( <ul className="list-group todobox"> { todos.map(function (todo,i) { return <TodoItem todo={todo} key={todo.id}/> }) } </ul> ) } componentDidMount(){ store.subscribe(function () { //7.store里的状态更新后,store.subscribe方法里的函数执行,view重新获取状态 this.setState({todos:store.getState().todos}) }.bind(this)) } } export default TodoBox removeTodo(id){ //3.view层产生用户操作,调用了actionCreator的方法 actions.removeTodo(id) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |