前端之家收集整理的这篇文章主要介绍了
React六——Redux,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
数据流
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.js
import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(reducer) //Redux 提供createStore这个函数,用来生成 Store。
export default store
2、创建reducer.js
reducer 纯函数
//第一个参数就是默认的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.js
import 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)
}
原文链接:https://www.f2er.com/react/302183.html