React组件之间传值不方便,所以用Rudex
准备
下载antd(有点像bootstrap) 下载redux (仓库)
项目目录进入cmd
yarn add antd
yarn add redux
下载duduxdevtools
在google商店中安装
使用Redux
创建store
在src中创建一个文件夹store
在store中创建index.js
创建reducer.js
注意:
store唯一
只有store能改变自己内容
reducer为纯函数
index.js
import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
reducer.js
const defaultState = {
inputValue:'',
list:[]
}
export default (state = defaultState,action) =>{
return state;
}
例子:当在input框中输入内容想要改变store中的内容时
首先创建一个活动接着把活动发送给Store
handleInputChange(e){
const action = {
type:'chage_input_value',
value:e.target.value
}
store.dispatch(action);
}
Store接收后进行改变,reducer不能直接改变值,所以先new一个新的State,修改后返回新的State回Store,这时候Store自动替换新的State进入仓库
const defaultState = {
inputValue:'1',
list:[1,2]
}
export default (state = defaultState,action) =>{
if (action.type === 'chage_input_value'){
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState;
}
// 初始化页面时运行
console.log(state,action);
return state;
}
添加同理
export default (state = defaultState,action) =>{
if (action.type === 'add_todo_item'){
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
return newState;
}
// 初始化页面
console.log(state,action);
return state;
}
为了方便debug,所以将actionTypes单独提出来在store下再创建一个文件actionTypes.js
export const CHANGE_INPUT_VALUE = 'chage_input_value'
export const ADD_TODO_ITEM = 'add_todo_item'
export const DELETE_TODO_ITEM = 'delete_todo_item'
将这个导入到上述文件中,使用起来查错更方便。
import {CHANGE_INPUT_VALUE , ADD_TODO_ITEM , DELETE_TODO_ITEM} from './store/actionTypes'
为了标准化 再在store下创建一个actionCreator.js 把要使用的acion都先定义好
actionCreator.js
import {CHANGE_INPUT_VALUE , ADD_TODO_ITEM , DELETE_TODO_ITEM} from './actionTypes'
export const getInputChangeAction = (value) => ({
type:CHANGE_INPUT_VALUE,
value
});
export const getAddItemAction = () =>({
type:ADD_TODO_ITEM
});
export const getDeleteItemAction = (index) =>({
type:DELETE_TODO_ITEM,
index:index
})
这样使用起来只需要在 TodoList.js 这样使用
import { getInputChangeAction , getAddItemAction , getDeleteItemAction } from './store/actionCreator'
handleInputChange(e){
const action = getInputChangeAction(e.target.value);
store.dispatch(action);
}
handleBtnClick(){
const action = getAddItemAction();
store.dispatch(action);
}
handelItemClick(index){
console.log(index);
const action = getDeleteItemAction(index);
store.dispatch(action);
}
}
export default TodoList;