搭建 RN 項目頁面不習慣的一些點

看著我們 RN 項目,下意識會類比以往 iOS 項目中的搭建思路,首先劃分基本差不多

我們某個頁面基本構成
  • api:請求接口
  • interface: 參數模型
  • style: 布局樣式
  • index.tsx: 引用調用
  • XXXPhone.tsx: 主頁面呈現 View(主要邏輯也在此)

確實我們平常搭建 iOS 頁面差不多的,只是換了種方式,只是在主頁面處有一些有意思的點,或者說從 iOS 角度看不習慣的點。

class RNTest extends React.Component {
  render() {
    return (
      <View style={styles.container}>
            XXXX
      </View>
    );
  }
}

不習慣的點,記錄于此:

  • 一、各種 const 聲明
  • 二、箭頭函數的不習慣
  • 三、useState
  • 四、useEffect
一、各種 const 聲明

在 iOS 中,我們一般沒有用直接用 const 的習慣,除了聲明常用值

隨便找一個頁面,這些 Const 看的我好不習慣啊,慢慢體會

可以說,按照我們之前 iOS 的說法,方法和屬性全都用 const 了

二、箭頭函數的不習慣
const closeModal = () => {
    setModel(false);
};
const getWithdrawalDetail = async (id: number) => {
  return await ApiWithdrawalDetail({ billId: `${id}` });
};
export const ApiWithdrawalDetail = (
  params: IWithdrawalParam
): Promise<IResponse<IWithdrawalResult>> => {
  return http.get('xxxx/detail', { params });
};

還好可以自動補全的 =() =>{}

三、useState

useState 也叫 State Hook, 是 Hooks 最常見的IPA, 俗稱狀態鉤子。
Hooks 是一種在函數式組件中使用有狀態函數的方法。

import React, { useState } from 'react';
import {
    SafeAreaView,
    Text,
    TouchableOpacity
} from 'react-native';
import Constants from './expand/dao/Constants';
import { post } from './expand/dao/HiNet';
export default (props: any) => {
    const [msg, setMsg] = useState('');
    const doFetch = () => {
        const formData = new FormData();
        formData.append("requestPrams", 'RN');
        post(Constants.test.api)(formData)().then(result => {
            setMsg(JSON.stringify(result));
        }).catch(e => {
            console.log(e);
            setMsg(JSON.stringify(e));
        })
    }
    return (
        <SafeAreaView>
            <TouchableOpacity onPress={doFetch}>
                <Text>加載</Text>
            </TouchableOpacity>
            <Text>{msg}</Text>
        </SafeAreaView>
    );
};

上述是網上一個很經典的例子, 可以很好的理解

const [steps, setSteps] = useState<IStep[]>([]);
const [withdrawal, setWithdrawal] = useState<IWithdrawalResult>();
setSteps(temp.data);
setWithdrawal(result.data);

上述該變量的值也就被修改了。而State Hook 的作用范圍:因為Hooks只能應用與函數式組件,所以通過它聲明的state的作用范圍是函數內。

四、useEffect

useEffect 也叫 Effect Hook, 也是 Hooks 最常見的IPA, 俗稱副作用鉤子。

我們可以把 useEffect Hook 看做React class 的生命周期函數:componentDidMountcomponentDidUpdatecomponentWillUnmount 這三個函數的組合。

import React, { useState, useEffect } from 'react';
import {
    SafeAreaView,
    StyleSheet,
    Text,
    TouchableOpacity
} from 'react-native';
import Constants from './expand/dao/Constants';
import { post } from './expand/dao/HiNet';
export default (props: { navigation: any }) => {
    const [msg, setMsg] = useState('');
    useEffect(() => {
        //對應componentDidUpdate
        function handleStatusChange(status: any) {
            console.log(status);
        }
        const timer = setTimeout(() => {
            doFetch();
        }, 2000);
        // 對應componentWillUnmount
        return function cleanup() {
            timer && clearTimeout(timer);
        };
    });
    const doFetch = () => {
        const formData = new FormData();
        formData.append("requestPrams", 'RN');
        post(Constants.test.api)(formData)().then(result => {
            setMsg(JSON.stringify(result));
        }).catch(e => {
            console.log(e);
            setMsg(JSON.stringify(e));
        })
    }
    return (
        <SafeAreaView>
            <TouchableOpacity onPress={doFetch}>
                <Text>加載</Text>
            </TouchableOpacity>
            <Text>{msg}</Text>
        </SafeAreaView>
    );
};

上述也是一個經典的使用 useEffect 的例子, 目前我直接理解成進入頁面刷新使用用到的點。

而單獨的刷新又可以用到 useCallback, 所以到后來感覺 React Native 開發,當我們熟悉常用的幾個鉤子( Hooks) 后加上之前的HTML CSS 基礎就可以開干啦。

參考
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。