感觉最近的学习已经回归到了React的底层,之前公司React的数据的时候已经架在了dva上,后再升级到dva+umi的框架之上,现在忙着准备java转前端的面试,只能再次学习了解一下Redux,切记先要安装redux哦(cnpm i redux --s),上代码吧
1.v层,负责页面的展示,此时需要将Store导入页面
import React,{Component} from 'react'
import {Button,Input,List} from 'antd'
import store from '../store'
//将此处的三个方法名设置为了常量,避免手写错误
import {DELETE_ITEM,ADD_TODO,CHANGE_INPUT} from '../ActionTypes'
import 'antd/dist/antd.css'
import './style.css'
export default class Todo extends Component{
constructor(props) {
super(props)
//走store中获取数据
this.state = store.getState()
this.handleStoreChange = this.handleStoreChange.bind(this)
//监听事件
store.subscribe(this.handleStoreChange)
}
handleChange(value){
//创建行为,将行为发store,由stroe来改变自己的内容
const action = {
type:CHANGE_INPUT,
value:value
}
store.dispatch(action)
}
handleStoreChange(){
this.setState(store.getState())
}
addTodo(){
store.dispatch({
type:ADD_TODO,
value:this.state.inputValue
})
}
deleteItem(index){
store.dispatch({
type:DELETE_ITEM,
value:index
})
}
render(){
return(
<div className='whole'>
<Input placeholder='请输入'
style={{width:'300px',marginRight:'10px'}}
value={this.state.inputValue}
onChange={(e)=>{this.handleChange(e.target.value)}}/>
<Button type='primary'
onClick={()=>this.addTodo()}>
添加
</Button>
<List style={{marginTop:'10px',width:'374px'}}
bordered
dataSource={this.state.list}
renderItem={(item,index) => (<List.Item
onClick={()=>{this.deleteItem(index)}}>
{item}
</List.Item>)}
/>
</div>
)
}
}
以下为未触发事件之前的效果图
2.创建好了Store,具体文件格式如下:
3. store/index.js
4. store/reducer.js
当我们修改input中的数据的时候,主页面store会将创建好的action发送到reducers中进行数据的修改,当数据修改完成后,返回store,主要的store.subscrbe对页面进行了监听,由数据改变时则将重新渲染页面
import {DELETE_ITEM,ADD_TODO,CHANGE_INPUT} from '../ActionTypes'
const defaultState={
inputValue:'',
list:[]
}
export default (state=defaultState,action)=>{
switch (action.type) {
case CHANGE_INPUT:
const newData = state
newData.inputValue = action.value
return newData
case ADD_TODO:
const newData1 = state
newData1.list.push(action.value)
newData1.inputValue=''
return newData1
case DELETE_ITEM:
const newData2 = JSON.parse(JSON.stringify(state))
newData2.list.splice(action.value,1)
return newData2
}
return state
}
在文本框中输入数据,input中的值改变,点击添加按钮,list中渲染出一条数据且将文本框的数据进行清空处理
Redux的三大原则:1.store是唯一的;2.只有store能够改变自己的内容,通过唯一的方式即action的触发来修改;3.Reducer必须是纯函数(所谓纯函数,即给定固定的输入就一定会有固定的输出,且不允许有任何的副作用)
当然在此Demo中也接触到了几个核心的API,createStore(创建store),store.dispatch(发送请求),store.getState(获取store中state的值),store.subscripe(监听)