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了。
拿到了商品的信息,我们就可以通过我们封装的方法,进行操作了。