react-native项目搭建

  • Post author:
  • Post category:其他




React-Native环境搭建


官方环境搭建地址

https://reactnative.cn/docs/environment-setup

react-native 0.63.3
node v12.10.0



初次运行注意项


1.react-native 0.65版本,xcode需12.0及以上,android studio需4.2及以上。

2.在pod install时某些资源需翻墙,或配置本地hosts,参考文章

https://juejin.cn/post/6844904193170341896



3.在必要的步骤进行后若报错,请使用xcode打开ios文件夹下的.xcworkspace文件运行,android打开android目录下的bulid.gradle文件运行,这样可以更快的找到错误。



真机运行


1.运行android环境建议使用真机运行,ios环境建议使用虚拟机运行,android虚拟机反应较慢,且内存占用较多。

2.android真机运行最好使用android studio运行,确保手机已连接至电脑,且电脑wifi及手机wifi在同一IP下,参考地址

https://www.react-native.cn/docs/0.63/running-on-device



3.ios真机运行时确保手机上已安装过该开发账户的app,或者在开发者网站上将设备加入至授权设备中,参考地址

https://www.react-native.cn/docs/0.63/running-on-device




React + React Hooks + Redux

yarn add redux react-redux redux-thunk

App.js

import React from 'react'
import NavigationComponent from './navigator'
import { Provider } from 'react-redux'
import store from './store'

/**
 * 应用入口文件
 */

function App() {
    return (
        <Provider store={store}>
            <NavigationComponent routeName={routeName} />
        </Provider>
    )
}

export default App

store

import { applyMiddleware, createStore } from 'redux'
import thunk from 'redux-thunk'
import reducers from '../reducer'

/**
 * 自定义log中间件
 * 关于中间件的更多解释可参考:https://cn.redux.js.org/docs/advanced/Middleware.html
 * @param store
 */

const logger = (store) => (next) => (action) => {
    if (typeof action === 'function') {
        console.log('dispatching a function')
    } else {
        console.log('dispatching ', action)
    }
    const result = next(action)
    console.log('nextState ', store.getState())
    return result
}

const middlewares = [logger, thunk]

export default createStore(reducers, applyMiddleware(...middlewares))

action

import fetch from '../../utils/fetch'
import Types from './types'

/**
 * 登录获取用户信息及token
 * @param {object}param 请求参数
 * @returns {function(*=)}
 */

function onChangeUser(data) {
    return (dispatch) => {
        dispatch({ type: Types.TOKEN_LOAD_STATUS, data })
    }
}

export default {
    onChangeUser,
}

reducer

import Types from '../../action/token/types'

// 定义初始数据
const defaultState = {
    isLoading: true,
    tokenLoading: true,
    data: null,
}

/**
 * 基于action type动态设置TOKEN是否有效状态
 * @param state
 * @param action
 * @returns {{TOKEN: (onAction|*|string)}}
 */

export default function onAction(state, action) {
    state = state || defaultState
    switch (action.type) {
        case Types.TOKEN_LOAD_STATUS: //token本地获取
            return {
                ...state,
                tokenLoading: false,
                data: action.data,
            }
        default:
            return state
    }
}

示例

import { useSelector } from 'react-redux'
const userInfo = useSelector((state) => state.token.data) || {}



版权声明:本文为weixin_43947842原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。