redux快速上手
redux快速上手用reflux存在问题我们cmdb项目目前是用react reflux 进行构建的,使用起来非常方便
当然在使用过程中也发现了一些问题
使用redux
redux的优点
step1:定义初始数据开始定义一个component的初始数据会定义在getInitialState中 getInitialState(){ return { list:[ {id:1,name:'数据1'},{id:2,name:'数据2'},{id:3,name:'数据3'},] } } 使用redux定义初始数据需要定义在一个reducer中,通过一个函数返回需要得到的数据 const initialState =[ {id:1,]; function reducer(state = initialState,action) { return state } step2:创建store通过redux的createStore方法创建唯一的store const store = createStore( reducer ) step3: 安装react-redux所有容器组件都可以访问 Redux store,可以使用React Redux 组件 <Provider> 来让所有容器组件都可以访问 store, import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore } from 'redux' import reducer from './reducer' import App from './components/App' let store = createStore(reducer) render( <Provider store={store}> <App /> </Provider>,document.getElementById('root') ) step4 component读取 state定义 mapStateToProps 这个函数来指定如何把当前 Redux store state 映射到展示组件的 props 中。 import React from 'react' import { connect } from 'react-redux' let App=React.createClass({ render(){ const {list}=this.props; return( <div> <ul> {list.map((item)=><Item key={item.id} item={item}/>)} </ul> </div> ) } }) const mapStateToProps = (state) => { return { list: state } } export default connect( mapStateToProps,)(App) step5 通过action修改redux中的数据export function deleteItem(id)=>{ return { type:'DELETE_ITEM',payload:{ id:id } }; } const initialState =[ {id:1,action) { switch (action.type) { case 'DELETE_ITEM': return state.filter(item=> item.id !== action.id ) default: return state } } step6 分发 action除了读取 state,connect()还能分发 action。可以定义 mapDispatchToProps() 方法, import React from 'react'; import {deleteItem} from '../actions/index' import { connect } from 'react-redux' let App=React.createClass({ render(){ const {list,deleteItem}=this.props; return( <div> <ul> {list.map((item)=><Item key={item.id} deleteItem={deleteItem} item={item}/>)} </ul> </div> ) } }) const mapStateToProps = (state) => { return { list: state } } const mapDispatchToProps = (dispatch) => { return { deleteItem: (id) => { dispatch(deleteItem(id)) } } } export default connect( mapStateToProps,mapDispatchToProps )(App) import React from 'react' let Item=React.createClass({ render(){ const {item}=this.props; return( <li> {item.name}<button onClick={()=>this.props.deleteItem(item.id))}}>删除</button> </li> ) } }) export default Item 参考redux 中文文档 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |