1. 组件命名文件夹
一个组件一个文件夹,可读性高,结构清晰
文件夹:Danamic(首字母大写) index.jsx style.less data.js
引用 :
import Danamic from './Danamic'
2. 无状态组件()
import React from 'react' import { render } from 'react-dom' function isEmpty(obj) { return obj === null || obj === undefined } export default ({ type,clickFn }) => { let text = '' switch ((isEmpty(type) ? '' : type).toString()) { case "2": text = '没有更多了' break case "1": text = '点击加载更多' break case "0": text = '网络加载问题,请稍后重试' break } return <div className="warning" onClick={clickFn}>{text}</div> }
少写下面这些代码
export default class extends React.Component { constructor(props) { super(props) } }
3. static react.propTypes
constructor(props) { super(props) } static propTypes = { info: React.PropTypes.object.isrequired,loginSuccess: React.PropTypes.func.isrequired,} function a() { } a.x a.prototype.y
加上propTypes 能一眼看出父组件传的参数以及类型
4. 提取数据请求
data.js
import React from 'react' import ajax from 'ajax-promise-simple' import loadPage from '@/common/loadPage' module.exports = { //获取全部评论 async getList(params) { let result = await ajax.getJSON('/amsquare/detailcomment',params) return { succsess: result.code === 0,data: result.data ? result.data : [] } },//点赞 async zanClick(params) { let result = await ajax.getJSON(`/amsquare/addcmtpraise`,params) // console.log(params) return { succsess: result.code === 0 } },//删除动态 async removeDT(params) { let result = await ajax.getJSON('/amsquare/deldymanic',params) if (result.code === 0) { const url = `http://wen.58.com/amsquare/main?from=weijiaoliu_nav`; const browser = window.____json4fe.browser; loadPage(url,browser,false) } },}
应用:
import { getList } from '../data' getListData = async () => { this.setState({ loading: true }) let { succsess,data } = await getList(this.infoConf) this.setState({ loading: false }) if (succsess) { this.setState((preState,props) => ({ hasMore: data.length < this.infoConf.pageSize ? false : true,resultStatus: data.length < this.infoConf.pageSize ? 2 : 1,list: [...preState.list,...data],})) this.infoConf.pageindex++; } else { this.setState({ resultStatus: 0 }) } }
5. 将多个组件放在一个index对外导出
import a import b import c module.exports={ a,b,c,d }
6. 提取封装 共用组件
例如:
引用:
import { scrollBottom,debounce } from '@/common/scrollData'
使用 @ 相当于src目录 (自动构建配置)
少用 ../ ./
7. 用let替换var
8. 代码加注释
9. webpack.config.js
resolve: { ... extensions: ['.ts','.tsx','.js','.json','.styl','.less'],... },
require的时候可以直接使用require('file'),不用require('file.js')
10.webpack 端口号随机
port: Math.floor(Math.random() * 1001) + 7000,
最近写文档比较多,所以把MarkDown整理了一遍,有需要可以参考:
原文链接:https://www.f2er.com/react/302547.html