教你如何在项目中如何将Redux写法更方便,更好维护
因每个页面都有所关联的,请将所有页面新建或修改完毕,再运行
1. 安装 Redux
npm install --save redux
2. 安装React-Redux
npm install --save react-redux
3.修改src/index.js
/* @Provider: 提供器-可以直接使用store @store: 将src/store/index.js 引用 */ import React from 'react'; import ReactDOM from 'react-dom'; import store from './store' import TodeList from './TodeList'; import { Provider } from 'react-redux' const App = ( <Provider store={store}> <TodeList /> </Provider> ) ReactDOM.render(App, document.getElementById('root'));
2. 创建/src/store/index.js
import { createStore } from 'redux' import reducer from './reducer' // 创建store库 const store = createStore(reducer) export default store
3. 创建/src/store/reducer.js
import { CHANGE_INPUT, ADD_ITEM, DEL_ITEM } from './actionType' const defaultState = { inputVal: 'hahah', list: [] } /* @state=defaultState:默认store定义值 @action:通过dispatch需要改变得值 @CHANGE_INPUT: input框change事件,改变得value与inputVal绑定 @ADD_ITEM: 点击提交按钮,将inputVal放入li中 @DEL_ITEM: 点击哪个li删除哪个 */ export default (state = defaultState, action) => { let newState = JSON.parse(JSON.stringify(state)) switch (action.type) { case CHANGE_INPUT: newState.inputVal = action.value break; case ADD_ITEM: newState.list.push(newState.inputVal) break; case DEL_ITEM: newState.list.splice(action.value, 1) break; default: return state break; } return newState }
4. 新建src/store/actionType.js
export const CHANGE_INPUT = 'change_input' export const ADD_ITEM = 'add_item' export const DEL_ITEM = 'del_item'
5. 新建src/store/actionCreated.js
import { CHANGE_INPUT, ADD_ITEM, DEL_ITEM } from './actionType' export const changeInputAction = (value) => ({ type: CHANGE_INPUT, value }) export const addItemAction = (value) => ({ type: ADD_ITEM, value }) export const delItemAction = (value) => ({ type: DEL_ITEM, value })
6.新建src/TodeList.js
/* @connect: 连接器-将state,dispatch连接在一起 connect(state, dispatch)(TodeList) @TodeList: 将TodeList封装成一个UI组件,并传入参数props,可以接受外部传的所有参数 */ import React from 'react'; import { connect } from 'react-redux' import { changeInputAction, addItemAction, delItemAction } from './store/actionCreated' const TodeList = (props) => { let { inputVal, inputChange, clickButton, list, delItem } = props return ( <div> <div> <input value={inputVal} onChange={inputChange} /> <button onClick={clickButton}>提交</button> </div> <ul> { list.map((item, index) => { return <li key={item + index} onClick={delItem.bind(this, index)}>{item}</li> }) } </ul> </div> ); } const stateToProps = (state) => { return { inputVal: state.inputVal, list: state.list } } const dispatchToProps = (dispatch) => { return { inputChange(e) { let action = changeInputAction(e.target.value) dispatch(action) }, clickButton() { let action = addItemAction() dispatch(action) }, delItem(value) { let action = delItemAction(value) dispatch(action) } } } export default connect(stateToProps, dispatchToProps)(TodeList);