Vue的响应能力,直接改变data()里面字段的值UI就会自动刷新,而react不会,如下代码:
import React from 'react';
import { Badge, TabBar, Button } from 'antd-mobile';
import {ScanningOutline,AppOutline,MessageOutline,MessageFill,UnorderedListOutline,UserOutline,
} from 'antd-mobile-icons';const Menu = () => {let products=[{ title: '卷心菜', isFruit: false, id: 1 },{ title: '大蒜', isFruit: false, id: 2 },{ title: '苹果', isFruit: true, id: 3 }];const ShoppingList = () => {return (<ul>{products.map(i => (<li key={i.id} style={{ color: i.isFruit ? 'magenta' : 'darkgreen' }}>{i.title}</li>))}</ul>);};return (<div style={{ padding: 20 }}><h2>菜单页面</h2><ShoppingList /><div><Button type="primary" onClick={() => {const productName = prompt('请输入产品名称');if (productName) {const newProduct = {title: productName,isFruit: false,id: products.length + 1};products=[...products, newProduct];}}}>添加11</Button></div></div>);
};
export default Menu;
直接改变products,界面中的products列表不会刷新。
这时候要引入状态管理器:
import React, { useState } from 'react';
import { Badge, TabBar, Button } from 'antd-mobile';
import {ScanningOutline,AppOutline,MessageOutline,MessageFill,UnorderedListOutline,UserOutline,
} from 'antd-mobile-icons';const Menu = () => {const [products, setProducts] = useState([{ title: '卷心菜', isFruit: false, id: 1 },{ title: '大蒜', isFruit: false, id: 2 },{ title: '苹果', isFruit: true, id: 3 }]);const ShoppingList = () => {return (<ul>{products.map(i => (<li key={i.id} style={{ color: i.isFruit ? 'magenta' : 'darkgreen' }}>{i.title}</li>))}</ul>);};return (<div style={{ padding: 20 }}><h2>菜单页面</h2><ShoppingList /><div><Button type="primary" onClick={() => {const productName = prompt('请输入产品名称');if (productName) {const newProduct = {title: productName,isFruit: false,id: products.length + 1};setProducts([...products, newProduct]);}}}>添加</Button></div></div>);
};
export default Menu;
需要注意的是useState要在组件内部使用!ShoppingList 可以放到组件外部,带上参数即可,如下:
...
// 将 ShoppingList 函数移到组件外部
const ShoppingList = (props) => {const { args } = props;return (<ul>{args.map(i => (<li key={i.id} style={{ color: i.isFruit ? 'magenta' : 'darkgreen' }}>{i.title}</li>))}</ul>);
};const Menu = () => {const [products, setProducts] = useState([{ title: '卷心菜', isFruit: false, id: 1 },{ title: '大蒜', isFruit: false, id: 2 },{ title: '苹果', isFruit: true, id: 3 }]);return (<div style={{ padding: 20 }}><h2>菜单页面</h2><ShoppingList args={products} /><div><Button type="primary" onClick={() => {const productName = prompt('请输入产品名称');if (productName) {const newProduct = {title: productName,isFruit: false,id: products.length + 1};setProducts([...products, newProduct]);}}}>添加</Button></div></div>);
};
export default Menu;
吐槽一下,React代码量要比vue多很多