极速小乌龟

导航

React redux基础语法(大白菜都能看懂)

第一步

创建文件夹:stroe

第二步

在store文件夹中创建index、reducer文件

第三步

store > index.js {

import {createStore} from 'redux';

import reducer from './reducer'
 
const store = createStore(
reducer,
// 配置谷歌插件Redux DevTools 查看更新redux数据走向
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

export default store;

}

 

store > reducer{

const defaultState={

inputValue:'',

list:[1,2]
}

/**
* 注意:reducer 可以接收state参数,但是绝对不能修改state参数,所以在执行action之前做一个简单的深度拷贝
* const newState=JSON.parse(JSON.stringify(state));
*/
 
export default (state=defaultState,action) => {
if(action.type==='TEXT_INPUT_VALUE'){
const newState=JSON.parse(JSON.stringify(state));
newState.inputValue = action.value
return newState
}

// 添加数组
if(action.type==='LIST_VALUE_PUSH'){
const newState=JSON.parse(JSON.stringify(state));
newState.list.push(action.value);
newState.inputValue="";
return newState
}

// 删除数组
if(action.type==='DELETE_LIST_KEY'){
const newState=JSON.parse(JSON.stringify(state));
newState.list.splice(action.index,1);
return newState
}
return state;
}

}

第四步

创建react组建,处理redux相应的逻辑,以下是简单的增加、修改(后续会增加redux的封装和更加简易的使用方法)

//创建react组建

import React, { Component } from 'react'
// 引入antd UI模版
import { Input, Button, List, Typography } from 'antd'
// 引入store,(注:在react文件中,会自动在文件夹寻找index文件,所以我这里就不写完整的引入地址)
import store from './store'
class AntdList extends Component {
constructor(props) {
super(props);
// console.log(store.getState())
this.state = {
// 获取reducer 数据
reduxStore:store.getState()
}
// 监听reduce值变化触发方法,重新请求redux数据赋值this.state
store.subscribe(this.handleStoreonChang);
}
// 输入
handleonChang=(e)=>{
// 监听输入框,创建action
const action={
type:'TEXT_INPUT_VALUE',
value:e.target.value
}
store.dispatch(action);
}
// 添加
handleActionList=()=>{
const action={
type:'LIST_VALUE_PUSH',
value:this.state.reduxStore.inputValue
}
store.dispatch(action)
this.handleStoreonChang()
}

// 删除
deleteListKey=(index)=>{
const action={
type:'DELETE_LIST_KEY',
index
}
store.dispatch(action)
}

// 重新请求redux数据赋值this.state
handleStoreonChang=()=>{
this.setState({
reduxStore:store.getState()
})
}


render() {
return(
<div>
<div>
<Input style={{width:300,}} value={this.state.reduxStore.inputValue} onChange={this.handleonChang}/>
<Button onClick={this.handleActionList}>确定</Button>
</div>
<div>
<List
style={{width:300}}
bordered
dataSource={this.state.reduxStore.list}
renderItem={(item,index) => (
<List.Item onClick={()=>{this.deleteListKey(index)}}>
<Typography.Text mark ></Typography.Text> {item}
</List.Item>
)}
/>
</div>
</div>
)

}
}

export default AntdList;

 

posted on 2020-03-10 00:10  极速小乌龟  阅读(345)  评论(0编辑  收藏  举报