Taro Best Practices Notes

1. 不能在包含JSX 元素的 map 循环中使用 if 表达式

2. 不能在Array.map 之外的方法中操作 JSX 数组

3. 不能在JSX参数中使用匿名函数

4.不支持在render() 之外的方法中定义JSX

所有的JSX定义,都要写在 render()中

> render(){
> const header = <View><Text>Header</Text></View>;
> const {showHeader} = this.state
>
> return (
> <View>
> {
> showHeader&&header
> }
> <View>
> <Text>Body</Text>
> </View>
> </View>
> )
> }
>

5. 不要再JSX的参数(props)中使用对象展开操作符

6. 不支持无状态组件

7.自定义组件样式不能受外部样式影响

即不要给自定义组件添加 className 或者 style 属性以期望控制自定义组件的展示

8.给自定义的组件设置 defaultProps 和 propTypes

class CustomComponent extends Component {
render(){
return (
<h1> Hello, {this.props.name}</h1>
);
}
}

CustomComponent.propTypes = {
name: PropTypes.String
};

CustomComponent.defaultProps = {
name: null
};

####9.组件传递函数属性以 on 开头

Class Parent extends Component {
handleEvent(){

}

render(){
return(
<CustomChild
onTrigger={this.handleEvent.bind(this)}
renderHeader={<JSX ></JS>}
>
</CustomChild>
)
}
}

10.不要在组件中打印传入的函数

11.不要将在模板中用到的数据设置为 undefined

如果某个数据不使用了,可以设置成 null

12.不要在组件中打印 this.props.chidren

13. props中可以传入JSX

组件传入的JSX的属性名必须以 render 开头

14. 属性值不能以 id,class,style 为名称

15. state 和 props 的字段不能重名

16.生命周期差异

— 在componentWillMount() 中即 onLoad 的时候才能拿到路由

— 子组件的 constructorrender 初始化时会被提前调用一次

17. JS编码必须使用单引号

18. 环境变量需要直接使用 process.env

19. 页面跳转时,在 componentWillMount() 前可以通过预加载拿到参数进行页面请求

> class Index extends Component{
>
> // Step 1.
> componentWillPreload(params) {
> // Step 2.
> return this.fetchData(params.url)
> }
>
> // Method Define
> fetchData () {
> this.isFetching = true
>
> }
>
> // Step 3.
> componentWillMount(){
> console.log('is Fetching: ', this.isFetching)
> this.$preloadData
> .then( res => {
> console.log( 'res', res)
> this.isFetching = false
> })
> }
> }
>
  1. 通过componentWillPreload接收页面跳转参数作为参数;
  2. componentWillPreload 中通过 return 将需要加载的内容返回;
  3. 在页面中触发 componentWillMount, 然后通过 this.$preloadData 获取到预加载的内容,然后再处理数据;

20. 使用this.$preload 函数进行页面跳转传参数

使用 this.$preload 可以传入单个参数也可以传入多个参数

this.$preload('key', 'val')
Taro.navigateTo({ url: '/pages/B/B'})

componentWillMount(){
console.log('preload: ', this.$router.preload.key)
}
this.$preload({
x: 1,
y: 2
})
Taro.navigateTo({ url: '/pages/B/B'})

componentWillMount(){
console.log('preload:', this.$router.preload)
}

21. 使用PurComponent减少不必要的渲染

class Home extends Taro.PureComponent {

}