React学习开发经验总结分享
Immutability Helper这是react官方文档推荐的方法(源代码很少) //更新数组中的某一条数据 updatePurchaseDetail(state,{ index,payload }) { return update(state,{ purchaseDetails: { [index]: { $merge: payload } } }) }, //向数组中添加一条数据 遵循不可变数据结构 我们不能直接用Push addPurchaseLine(state,{ item }) { return update(state,{ purchaseDetails: { $push: [item] } }) }, const collection = [1,2,{a: [12,17,15]}]; const newCollection = update(collection,{ 2: { a: { $splice: [[1,1,13,14]] // [1,14]对应于数组的splice函数的参数 } } } ); // => [1,14,15]}] // 在collection数组索引2的对象的a属性的数组的索引1的位置插入13,14 考虑使用函数式的setStatereact官方文档中这样介绍setState的
updateState({target}) { this.setState(prevState => { const updatedUser = {...prevState.user,[target.name]: target.value}; // 使用先前的state来构建新的state的值 doSomething(updatedUser); return { user: updatedUser }; }); } 使用PureComponent大家都知道使用好 class CounterButton extends React.Component { constructor(props) { super(props); this.state = {count: 1}; } shouldComponentUpdate(nextProps,nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; } return false; } render() { return ( <button color={this.props.color} onClick={() => this.setState(state => ({count: state.count + 1}))}> Count: {this.state.count} </button> ); } } 使用内联函数与传递props的问题在react中使用内联函数(在render方法里面定义的函数,并通过props传递到子组件)是很方便的,但是这样用也会影响应用的性能。 class MyComponent extends React.Component { render() { const msg = "Hello " + this.props.user.name.first; return <PureChild onClick={() => this.props.onAlert(msg)} />; //另一种形式 this.props.onAlert.bind(this,msg) } } 如何避免使用inline function ... //同一个函数需要处理多种情况的时候 handleClick = (ev) => { const { action } = ev.target.dataSet this.props.dispatch({ type: 'handleBpm',action }) } ... <Button data-action="Approve" onClick={this.handleClick}>approve</Button> <Button data-action="Reject" onClick={this.handleClick}>reject</Button> 2.把事件处理函数移到子组件 // 父组件 ... render () { const msg = "Hello " + this.props.user.name.first; return ( <PureChild onAlert={this.props.onAlert} msg={msg} /> ) } // 子组件 PureChild handleClick = () => { //do something const { onAlert,msg } = this.props; onAlert(msg) } ... render () { return ( ... <div onClick={this.handleClick}></div> ) } 第二种方法需要我们在可以编码子组件的情况下才可以做到 区分Container与ComponentContainer与Component的主要区别在于: 1.Container是跟全局状态有关联的,通常被用来管理数据并通过connect函数连接到全局state,几乎不写样式 2.Component与样式联系紧密,但是不参与管理任何数据,只通过接收到的props响应数据更改 在dva中routes下面的文件目录相当于containers,也就是说我们需要使用connect的组件就应该规划在这里面。 另外每一个文件夹的入口文件可以用index.js命名,这样有两个明显的好处。第一点是可以让阅读代码的人,一眼就知道在当前目录下,哪个文件是入口文件。第二点是在其他文件Import目标文件的时候,只需要写到folderName的位置就可以了。webpack会自动读取当前文件目录下的index文件。 关于react规范结构的问题 可以参考 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |