设置默认值,传递参数

解决问题

  1. 默认值设置
  2. 多余参数传递

代码

/* Bottom.component.js */ 
// ViewSheets 组件包装了 BottomSheets组件
exports const ViewSheets = ({ visible = false, items = [], onPress = () => null, ...props }) => {
    return (
        <BottomSheets visible={visible} {...props}>
            {items.map((actionName, i) => {
                return (
                    <ActionItem activeOpacity={1} onPress={() => onPress(i)} key={i}>
                        <ActionName>{actionName}</ActionName>
                    </ActionItem>
                )
            })}
        </BottomSheets>
    )
}

/* index.js */
<ViewSheets 
    visible={true} 
    items={[1,2,3]}
    onPress={() => {console.log('我在 ViewSheets 中触发')}}
    onCancelPress={() => {'我在 BottomSheets 中触发'}}
   />

组件注入式请求,与外部触发加载

解决问题

  1. 一个组件请求接口不同,返回数据相同,展现相同
  2. 组件外部,状态改变,组件需要初始化
  3. 通用逻辑与展现,统一管理。

代码

/* Goods.component.js */ 
const initialState = {
    goodsList: [],
    pageNum: 1,
    pageSize: 12,
    lastPage: false, // 最后一页
    empty: false, // 空数据
    reachBottom: false // 下拉加载
}

const reducer = (state, action) => {
    switch (action.type) {
        case 'update': {
            return { ...state, ...action.payload }
        }
        default:
            return state
    }
}

export const Goods = ({fetch, stickyHeaderComponent = null, ...arg}) => {
    const [goods, dispatch_goods] = useReducer(reducer, initialState) // useReducer 为函数提供Redux的功能
    const {goodsList, pageNum, pageSize} = goods // 解构对象,方便使用 
    const isLoading = useRef(null) // 防多次调用
    
    useEffect(() => {
      if(fetch){
         isLoading.current = true
         
         // 数据初始化
         dispatch_goods({
           type: 'update',
           payload: {
             pageNum: 1,
             lastPage: false, 
             empty: false, 
             reachBottom: false 
           }
         })
         getGoods({pageNum: 1})  
      }
    },[fetch])
    
    const getGoods = params => {
      fetch({...params, pageSize})
         .then(json => {
            const { hasNext, data } = json

            dispatch_goods({
                type: 'update',
                payload: {
                    goodsList: params.pageNum === 1 ? data : goodsList.concat(data),
                    lastPage: !hasNext,
                    empty: params.pageNum === 1 && data.length === 0,
                    reachBottom: false
                }
            })
         })
         .finally(() => {
             isLoading.current = false
         })
    }
    
    // 下拉加载
    const handleEndReached = () => {
        if (lastPage || isLoading.current) {
            return
        }

        isLoading.current = true
        dispatch_goods({
            type: 'update',
            payload: {
                reachBottom: true,
                pageNum: pageNum + 1
            }
        })
        getGoods({ pageNum: pageNum + 1 })
    }
    
    return (
       <FlatList ...arg />
    )
}


/* index.js */
import { goodsQuery, goodsByShop } from '../service;

export const SearchGoodsScreen = ({navigation}) => {
   const supplierId = navigation.getParam('supplierId', '')
   // 初始化
   const [searchGoods, dispatch_searchGoods] = useReducer(reducer, {
        filterData: {
            areaId: areaId,
            supplierId: supplierId,
            parentCategoryId: parentCategoryId,
            longCode: parentCategoryId,
            vagueSearch: searchValue,
            startTime: '',
            endTime: '',
            sort: 'spu.CREATED desc'
        }
    })
   const { filterData } = searchGoods
    
   const goodsFetch = useCallback(
        params => {
            if (supplierId) {
                // 查询店铺里面商品
                return goodsByShop({ ...filterData, ...params })
            } else {
                // 查询全部商品
                return goodsQuery({ ...filterData, ...params })
            }
        },
        [searchGoods]
   )
   
   // 查询触发goods加载
   const handleSearchSubmit = text => {
        dispatch_searchGoods({
            type: 'update',
            payload: {
                filterData: { ...filterData, vagueSearch: text }
            }
        })
   }
   
   return (
       <Goods
          fetch={goodsFetch}
          onEndReachedThreshold={0.2}  // FlatList 参数
       />
   )
}

LuDongWei
620 声望20 粉丝

英语不擅长的前端工作者