remax的containers在微信小程序的使用

remax的containers在微信小程序的使用

   在微信小程序中,我们如何保存一个常在的状态,列如,加入购物车的商品。

方法有很多,列如,可以通过本地存储,也可以通过状态管理器,例如vuex,Redux等。但在微信小程序中使用这些,会加大项目的体积,有什么好的方法的不用安装这些呢。这时,我们就可以使用containers来存储东西。这东西是什么呢?我也不是很清楚,但知道怎么用就可以了。

1 先创建一个containers文件夹。

2.创建添加和移出购物车的商品方法。列如

import * as React from 'react';
import {createContainer} from 'unstated-next';
import list from "less/lib/less/functions/list";

// 用户的购物车
function useShopCar() {
    const [list, setList] = React.useState([]);

    function add(item) {
        if (!list.includes(item)) {
            item.active = true;
            list.push(item);
        }
        setList([...list]);
    }

    function remove(item) {
        list.splice(list.findIndex(cItem => item === cItem), 1);
        setList([...list]);
    }

    return {
        list,
        add,
        remove,
        setList
    };
}

const ShopCar = createContainer(useShopCar);

export default ShopCar;

看到其中,我们封装了两个方法,一个add添加商品,一个remove移出商品。而list这个数组,就是我们存储的商品信息。

3.使用我们封装的方法
首先最重要的一步,就是在app.js文件中挂载。没有这一步,就会报错了。

import * as React from 'react';
import ShopCar from "./containers/ShopCar";
import './app.css';

// const App = props => props.children;
const App = ({ children }) => <ShopCar.Provider>{children}</ShopCar.Provider>;
export default App;

后面就可以在我们需要用到地方引用了。

import * as React from 'react';
import ShopCar from "../../containers/ShopCar";

export default () =>{
const shopCar = ShopCar.useContainer();
const addCar = (item) => {
  if (shopCar.list.includes(item)) {
      item.active = false;
      shopCar.remove(item);
      showToast({ title: '取消加入购物车', icon: 'none' }).catch();
    } else {
      shopCar.add(item);
      showToast({ title: '已加入购物车', icon: 'none' }).catch();
    }
  };
}

代码解析:
addCar是我们封装一个事件,当我们点击这个事件的时候,就会给我们传商品的信息,也就是item了。
拿到了商品的信息,我们就可以通过我们封装的方法,进行操作了。

自己学习使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值