这篇文章是建立在我上篇文章《从零开始搭建react项目》基础了配置的哟~,这里我以做一个简单的Todolist来使用Radux哈
一、我们使用Radux,必不可少的一步当然是安装radux
1、执行npm i redux -S
2、执行npm i react-redux -S
二、首先在页面把todolist页面显示出来,在views创建todolist文件夹
1、创建TodoList.js页面组件
import React from 'react'
export default function TodoList() {
return (
<div>TodoList</div>
)
}
2、在SideMenu.js添加todolist菜单
const menu = [
// ...
{
id: 3,
title: "todolist",
key: "/todolist",
children: []
}
]
//...
3、在MainRouter.js引入TodoList.js页面组件
// ...
import TodoList from '@/views/todolist/TodoList';
export default function NewsSandBoxRouter() {
return (
<Switch>
{/* ... */}
<Route path='/todolist' component={TodoList}></Route>
{/* ... */}
</Switch>
)
}
三、改造TodoList.js页面组件
import React, {useState} from 'react';
import {Input,Button,List} from 'antd'
function TodoList(props){
// 这是状态
const [inputValue,setInputValue] = useState('')
const [list,setList] = useState([])
// 监听改变 input的value
const changeInput = (e) => {
setInputValue(e.target.value)
}
// 增加列表数据
const addBtn = () => {
list.push(inputValue)
setList([...list])
setInputValue('')
}
// 点击当前item 删除
const deleteItem = (index) => {
list.splice(index,1)
setList([...list])
}
return (
<div style={{margin:'10px'}}>
<div style={{marginBottom:'10px'}}>
<Input value={inputValue} style={{width:'400px',marginRight:'10px'}} type="text" placeholder='请输入内容' onChange={changeInput}/>
<Button type='primary' onClick={addBtn}>增加</Button>
</div>
<List bordered dataSource={list} renderItem={(item,index) =>(
<List.Item key={index} onClick={()=>{deleteItem(index)}}>{item}</List.Item>
)}></List>
</div>
);
}
export default TodoList;
显示效果
上面是普通添加todolist的方式,接下来我们通过radux的方式来增加todolist
前戏已经完成,下面正式进入主题。
四、使用react-redux
1、在src/index.js根元素加入Provider
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux'; // 引入 Provider
import store from './store'
ReactDOM.render(
// 把store 挂载到Provider上面使下面全局可以获取store里面数据
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
2、在store文件夹创建actionCreatores.js
、actionTypes.js
、reducer.js
、index.js
挂载store
//index.js
import { createStore, applyMiddleware, compose} from 'redux';
//当我们有从接口请求的数据需要存储到redux中时候,我们可以直接在redux发送网络请求,相当于一个中间件,当我们请求的时候可以做一些事,类似expree和koa
// import thunk from 'redux-thunk'; //处理redux里面的异步请求
//应用一些中间件
// const storeEnhancer = applyMiddleware(thunk)
// const store = createStore(reducer,storeEnhancer)
import reducer from './reducer';
//增强函数 compose 实现中间件的功能
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const store = createStore(reducer,composeEnhancers());
export default store;
reducer是一个函数,它接受一个state和一个action,根据action的type返回一个新的state。
根据actiontypes处理action的value,返回新的state
//reducer.js
const defaultObj = {
inputValue:"",
list:[]
}
const reducers = (state = defaultObj,action)=>{
// 监听 dispatch分发 执行 changeInput
if(action.type === 'changeInput'){
let newState = JSON.parse(JSON.stringify(state))
newState.inputValue = action.value;
return newState;
}
// 监听新增 dispatch分发
if(action.type === 'addItem'){
let newState = JSON.parse(JSON.stringify(state))
newState.list.push(newState.inputValue)
newState.inputValue = ''
return newState;
}
// 监听删除 dispatch分发
if(action.type === 'deleteItem'){
let newState = JSON.parse(JSON.stringify(state))
newState.list.splice(action.index,1)
return newState;
}
return state;
}
export default reducers;
统一管理action分发类型
//actionTypes.js
export const CHANGE_INPUT_TYPE = 'changeInput'
export const ADD_ITEM_TYPE = 'addItem'
export const DELETE_ITEM_TYPE = 'deleteItem'
根据类型统一通过dispatch 分发action模块化
//actionCreatores.js
import {
CHANGE_INPUT_TYPE,
ADD_ITEM_TYPE,
DELETE_ITEM_TYPE,
} from './actionTypes'
export const changeInputAction = (value)=>({
type:CHANGE_INPUT_TYPE,
value
})
export const addItemAction = ()=>({
type:ADD_ITEM_TYPE
})
export const deleteItemAction = (index)=>({
type:DELETE_ITEM_TYPE,
index
})
3、改造TodoList.js,使用redux控制
import React from 'react';
import {Input,Button,List} from 'antd'
import {connect} from 'react-redux'
import {changeInputAction,addItemAction,deleteItemAction} from '@/store/actionCreatores'
function TodoList(props){
let {inputValue,changeInput,addBtn,list,deleteItem} = props;
return (
<div style={{margin:'10px'}}>
<div style={{marginBottom:'10px'}}>
<Input value={inputValue} style={{width:'400px',marginRight:'10px'}} type="text" placeholder='请输入内容' onChange={changeInput}/>
<Button type='primary' onClick={addBtn}>增加</Button>
</div>
<List bordered dataSource={list} renderItem={(item,index) =>(
<List.Item key={index} onClick={()=>{deleteItem(index)}}>{item}</List.Item>
)}></List>
</div>
);
}
//映射props
const mapStateToProps = (state) => {
return {
inputValue:state.inputValue,
list:state.list
}
}
const mapDispatchToProps = (dispatch)=>{
return {
changeInput(e){
let action = changeInputAction(e.target.value)
dispatch(action)
},
addBtn(){
let action = addItemAction();
dispatch(action)
},
deleteItem(index){
let action = deleteItemAction(index);
dispatch(action)
}
}
}
//连接器 创建映射关系
const VisibleTodoList = connect(mapStateToProps, mapDispatchToProps)(TodoList)
export default VisibleTodoList;
以上就是todolist使用redux全部配置,同样实现了增加、删除功能
demo地址 React-base
代码地址 github