雖然常用的編碼用一種即可,但是看別人文檔或者示例時,有的寫法不熟悉的話看着很不習慣,整理幾種實現同一功能的不同寫法
1、Dva Connect與@Connect
import React, { Props } from 'react';
import { Button, Input } from 'antd';
import { connect } from 'dva';
//@connect(()=>({"age":111}))
class Demo extends React.Component {
constructor(props) {
super(props);
}
render(){
return(<div>{this.props.age}</div>);
}
}
//export default Demo;
export default connect(()=>({"age":111}))(Demo);
//大括號被解釋偽代碼塊,所以如果箭頭函數直接返回一個對象,必須在對象外邊加上括號,類似一個轉義,箭頭函數本身默認return
箭頭函數:僅僅當箭頭函數為單行的形式時,才會出現隱式的return。當箭頭函數伴隨着{}被聲明,那么即使它是單行的,它也不會有隱式return
有篇講的全的:https://www.cnblogs.com/mengff/p/9656486.html
2、組件定義,主要三種,示例
class Test extends Component {
function Test(props) {
class Test extends PureComponent {
function Test<P>(params?: any){
const Test: React.FC<TestProps> = (props) => {
參考下面兩個鏈接文章
https://www.jianshu.com/p/2d00885a6d59
https://www.cnblogs.com/V587Chinese/p/11520674.html
3、props屬性紅色下划線,使用typescript的話,interface用於限定props屬性,如果不使用interface的話會有很多紅下划線,看着很刺眼
以比較復雜的Redux中的dispatch為例,
方法一:聲明interface
import { AnyAction } from 'redux';
export interface UserProps extends Dispatch<AnyAction> { dispatch: Dispatch<AnyAction>; }
class User extends React.Component<UserProps>
.......
通過以上三個步驟可解決紅線問題
方法二:
(props as any).dispatch
