React-Redux与MVC风格
前言
??刚接触React的时候,有人感叹这不就是当年的JSP吗?直接用代码生成html,两者混在一起,还真有不少人喜欢把事件响应和业务逻辑都写在component里面,看起来就头疼。当年的JSP已经被MVC所终结,我们可以借鉴MVC的思想让React-Redux的代码好写又好看。 先回顾一下MVC思想,如下图:??用户的请求先由Controller进行处理,处理后的数据放入Model,View根据Model的数据渲染界面呈现在用户面前。 React-Redux中应用MVC1. Model 对应Redux store import {reducer as common} from ‘./commonAction‘ import {reducer as online} from ‘./onlineAction‘ export default combineReducers({ common,online,}) 2. View 对应React component import {actions} from ‘./action‘; class Login extends Component { componentWillMount() { this.props.clearSession(); } render() { const p = this.props; return ( <div className="form"> <div className="input-group"> <label>User Name</label> <input type="text" value={p.s.username} onChange={e=>p.updateFormValue({username: e.target.value})} > </div> <div className="input-group"> <label>Password</label> <input type="password" value={p.s.password} onChange={e=>p.updateFormValue({password: e.target.value})} > </div> <div className="input-group"> <button type="button" className="btn btn-block" disabled={!p.s.loginReady} onClick={p.submitLogin} >Login</button> </div> </div> ) } } export default connect( store => ({ s: store.online }),{ ...actions } )(Login); 3. Controller 对应action,reducer const types = { UPDATE_VALUE: ‘ONLINE/UPDATE_VALUE‘,} export const actions = { updateValue: values => (dispatch,getStore) => { dispatch({type: types.UPDATE_VALUE,...values}); },} const initStore = { username: ‘‘,password: ‘‘,} export const reducer = (store={...initStore},action) => { switch (action.type) { case types.UPDATE_VALUE: return {...store,...action}; default: return {...store}; } } ??把负责更新数据的action type,action,reducer合并成一个文件。有些教程说,每个变量都要一个特定的action type,action creator和reducer中的case。在我看来是没有意义的,一个数据更新action就够模块里面所有变量使用了,而且可以一次更新多个变量,在接收后台数据时提高效率。 import {actions as onlineActions} from ‘../redux/onlineAction‘; export const actions = { updateFormValue: value => (dispatch,getStore) => { dispatch(onlineActions.updateValue(value)); dispatch(actions.verifyValue()); },verifyValue: () => (dispatch,getStore) => { const {username,password} = getStore().online; let loginReady = username.length >= 6; loginReady = loginReady && password.length >= 6; dispatch(onlineActions.updateValue(loginReady)); },submitLogin: () => (dispatch,getStore) => { const {username,password} = getStore().online; // submit data to server ... } } ???这里讨论了一种React-Redux项目的参考编码风格,让代码看起来有MVC感觉,好写好看。???另外,thunk只是入门级的中间件,对自己有要求的同学应该去学习一下saga。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |