本文最后更新于 128 天前,其中的信息可能已经有所发展或是发生改变。
React 中的常用方法
1、合并数组
代码语言:javascript复制// 合并数组并去重
mergeArray = (arr1, arr2) => {
return Array.from(new Set([...arr1, ...arr2]));
};
2、合并数组对象
代码语言:javascript复制// 合并具有相同属性的对象
mergeObject = (needObj, neededObj) => {
let obj = {};
return needObj.concat(neededObj).reduce((pre, cur) => {
if (!obj[cur.id]) {
obj[cur.id] = true;
pre.push(cur);
}
return pre;
}, []);
};
3、数据格式化
代码语言:javascript复制// 金额千分位
formatNumber = (value) => {
value = "";
const list = value.split(".");
const prefix = list[0].charAt(0) === "-" ? "-" : "";
let num = prefix ? list[0].slice(1) : list[0];
let result = "";
while (num.length > 3) {
result = `,${num.slice(-3)}${result}`;
num = num.slice(0, num.length - 3);
}
if (num) {
result = num result;
}
return `${prefix}${result}${list[1] ? `.${list[1]}` : ""}`;
};
4、state 的使用
代码语言:javascript复制只针对类组件,函数组件使用hook
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
str = 'abc',
arr = [1,2,3],
obj = {
a:1,
b:2,
c:3
}
};
}
componentDidMount() {
this.changeData();
}
changeData = ()=>{
const newObj = {
a:4,
b:5,
c:6,
d:7,
e:[1,2,3]
}
this.setState({
str:'def',
arr = [4,5,6],
obj: Object.assign({}, this.state.obj, newObj)
})
}
render() {
const{str,arr,obj} = this.state
return (
<div>
<h1>{str}</h1>
<h1>{arr}</h1>
<h1>{obj}</h1>
</div>
);
}
}
5、dva 的使用
代码语言:javascript复制当前项目 src 文件下需要有 models 文件夹
// 路由配置
'/test': {
component: dynamicWrapper(
app, ['testModel'], () =>
import('../routes/Test')
),
name: 'Test',
},
// 页面中
import { connect } from 'dva';
@connect(({ testModel }) => ({ ...testModel }))
//test.js
import request from '@/utils/request';
export async function GetNameList(params) {
return request(`http://localhost:8000/api/test/GetNameList`, {
method: 'POST',
body: params
});
}
//testModel.js
import * as service from '../../services/test'
export default {
namespace: "testModel",
state: {
nameList: ["Jerry"]
},
effects: {
// 异步方法
getNameList({ payload, callback }, { call, put }) {
const result = yield call(service.GetNameList, payload);
yield put({
type: 'returnData',
payload: result,
});
if (callback) {
callback(result);
}
}
},
reducers: {
// 同步方法(静态方法)
returnData(state, action) {
const result = action.payload;
let dataSource = result.data;
return {
...state,
dataSource,
};
},
},
};