通用评论 vedio

App.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import React, { Component } from "react";
  2. import PropTypes from "prop-types";
  3. import { message } from "antd";
  4. import axios from "axios";
  5. import { ERROR_DEFAULT, LIMIT, COMMENT_TYPE } from "./constant";
  6. import { CommentContext } from "./Comment";
  7. import { isFunction } from "./helper";
  8. import CommentInput from "./components/CommentInput";
  9. import CommentList from "./components/CommentList";
  10. import Editor from "./components/Editor";
  11. import RenderText from "./components/RenderText";
  12. import lang from "./lang";
  13. import "./App.css";
  14. // import styles from "./App.module.css";
  15. class App extends Component {
  16. constructor(props) {
  17. super(props);
  18. this.state = {
  19. loading: {},
  20. // oss 配置
  21. oss: {},
  22. // 评论数据
  23. list: [],
  24. page: 1,
  25. total: 0,
  26. // 是否没有更多评论了
  27. isNoMoreComment: false
  28. };
  29. this.handleChangeLoading = this.handleChangeLoading.bind(this);
  30. this.sCreateComment = this.sCreateComment.bind(this);
  31. this.sDeleteComment = this.sDeleteComment.bind(this);
  32. this.sCommentFavor = this.sCommentFavor.bind(this);
  33. this.sCreateReply = this.sCreateReply.bind(this);
  34. this.sDeleteReply = this.sDeleteReply.bind(this);
  35. this.errorHandler = this.errorHandler.bind(this);
  36. this.sGetComment = this.sGetComment.bind(this);
  37. this.sReplyFavor = this.sReplyFavor.bind(this);
  38. this.sGetReply = this.sGetReply.bind(this);
  39. this.sOssSts = this.sOssSts.bind(this);
  40. }
  41. componentWillMount() {
  42. this.axios = axios;
  43. this.axios.defaults.withCredentials = true;
  44. if (this.props.token) {
  45. this.axios.defaults.headers.common["Authorization"] = `Bearer ${
  46. this.props.token
  47. }`;
  48. }
  49. }
  50. componentDidMount() {}
  51. error(msg, info = {}) {
  52. if (this.props.showError) {
  53. message.error(msg);
  54. }
  55. if (this.props.onError) {
  56. this.props.onError(msg, info);
  57. }
  58. }
  59. errorHandler(error) {
  60. if (error.response && error.response.data && error.response.data.msg) {
  61. this.error(lang[error.response.data.msg] || ERROR_DEFAULT, {
  62. response: error.response
  63. });
  64. return;
  65. }
  66. this.error(lang[error.message] || ERROR_DEFAULT, {
  67. response: error.response
  68. });
  69. }
  70. /**
  71. * 改变 loading 状态
  72. * @param {string} key key
  73. * @param {string} value value
  74. */
  75. handleChangeLoading(key, value) {
  76. const { loading } = this.state;
  77. loading[key] = value;
  78. this.setState({ loading });
  79. }
  80. /**
  81. * 获取评论列表
  82. */
  83. sGetComment({ page = 1 } = {}) {
  84. const { pageType } = this.props;
  85. this.handleChangeLoading("sGetComment", true);
  86. const { API, type, businessId } = this.props;
  87. this.axios
  88. .get(
  89. `${API}/comments?type=${type}&business_id=${businessId}&page=${page}&limit=${LIMIT}`
  90. )
  91. .then(response => {
  92. const { list, page, total } = response.data;
  93. if (list) {
  94. let newList = list;
  95. let { list: oldList } = this.state;
  96. if (pageType === "more") {
  97. if (page > 1) {
  98. // 删除临时数据
  99. oldList = oldList.filter(o => !o.isTemporary);
  100. newList = oldList.concat(newList);
  101. }
  102. } else if (pageType === "pagination") {
  103. // TODO 滚动到顶部
  104. window.scrollTo(0, 0);
  105. }
  106. this.setState({
  107. list: newList,
  108. page,
  109. total
  110. });
  111. } else {
  112. message.info("没有更多评论了");
  113. this.setState({
  114. isNoMoreComment: true
  115. });
  116. }
  117. })
  118. .catch(this.errorHandler)
  119. .finally(() => {
  120. this.handleChangeLoading("sGetComment", false);
  121. });
  122. }
  123. /**
  124. * 获取更多回复
  125. */
  126. sGetReply({ commentId, page = 1 } = {}) {
  127. this.handleChangeLoading("sGetReply", true);
  128. const { API } = this.props;
  129. this.axios
  130. .get(`${API}/replies?comment_id=${commentId}&page=${page}&limit=${LIMIT}`)
  131. .then(response => {
  132. if (!response.data.list) {
  133. message.info("没有更多数据了!");
  134. }
  135. const list = this.state.list.map(item => {
  136. if (item.id === commentId) {
  137. if (!item.replies) item.replies = [];
  138. if (response.data.list) {
  139. if (page === 1) {
  140. // 如果当前页数为第一页,则清空当前所有的 replies
  141. // 并将获取到的 replies 存放在 state
  142. item.replies = response.data.list;
  143. } else {
  144. item.replies = item.replies
  145. .filter(o => !o.isTemporary)
  146. .concat(response.data.list);
  147. // 如果当前页数非第一页,则合并 replies
  148. }
  149. item.reply_count = response.data.total;
  150. item.reply_page = response.data.page;
  151. } else {
  152. item.isNoMoreReply = true;
  153. }
  154. }
  155. return item;
  156. });
  157. this.setState({ list });
  158. })
  159. .catch(this.errorHandler)
  160. .finally(() => {
  161. this.handleChangeLoading("sGetReply", false);
  162. });
  163. }
  164. /**
  165. * 添加评论
  166. * @param {object} {content} comment content
  167. */
  168. sCreateComment({ content } = {}, cb) {
  169. if (!content) return this.error("评论内容不能为空 ");
  170. this.handleChangeLoading("sCreateComment", true);
  171. const { API, type, businessId } = this.props;
  172. this.axios(`${API}/comments`, {
  173. method: "post",
  174. data: {
  175. type,
  176. business_id: businessId,
  177. content
  178. },
  179. withCredentials: true
  180. })
  181. .then(response => {
  182. if (this.props.showAlertComment) {
  183. message.success("评论成功!");
  184. }
  185. if (isFunction(cb)) cb();
  186. // 将数据写入到 list 中
  187. // 临时插入
  188. // 等到获取数据之后,删除临时数据
  189. const { list, total } = this.state;
  190. list.unshift({
  191. ...response.data,
  192. isTemporary: true // 临时的数据
  193. });
  194. this.setState({ list, total: total + 1 });
  195. })
  196. .catch(this.errorHandler)
  197. .finally(() => {
  198. this.handleChangeLoading("sCreateComment", false);
  199. });
  200. }
  201. /**
  202. * 删除评论
  203. */
  204. sDeleteComment(commentId) {
  205. this.handleChangeLoading("sDeleteComment", true);
  206. const { API } = this.props;
  207. this.axios(`${API}/comments/${commentId}`, {
  208. method: "delete",
  209. withCredentials: true
  210. })
  211. .then(() => {
  212. const { list, total } = this.state;
  213. const res = list.filter(item => item.id !== commentId);
  214. this.setState({ list: res, total: total - 1 });
  215. this.props.onDelete(COMMENT_TYPE.COMMENT);
  216. })
  217. .catch(this.errorHandler)
  218. .finally(() => {
  219. this.handleChangeLoading("sDeleteComment", false);
  220. });
  221. }
  222. /**
  223. * 添加回复
  224. * 回复评论/回复回复
  225. * @param {object} data { comment_id, content, [reply_id] }
  226. */
  227. sCreateReply(data, cb) {
  228. if (!data.content) return this.error("回复内容不能为空 ");
  229. this.handleChangeLoading("sCreateReply", true);
  230. const { API } = this.props;
  231. this.axios(`${API}/replies`, {
  232. method: "post",
  233. data,
  234. withCredentials: true
  235. })
  236. .then(response => {
  237. if (this.props.showAlertReply) {
  238. message.success("回复成功!");
  239. }
  240. if (isFunction(cb)) cb();
  241. // 将数据写入到 list 中
  242. // 临时插入
  243. // 等到获取数据之后,删除临时数据
  244. const list = this.state.list.map(item => {
  245. if (item.id === data.comment_id) {
  246. if (!item.replies) item.replies = [];
  247. item.replies.push({
  248. ...response.data,
  249. isTemporary: true // 临时的数据
  250. });
  251. item.reply_count += 1;
  252. }
  253. return item;
  254. });
  255. this.setState({ list });
  256. })
  257. .catch(this.errorHandler)
  258. .finally(() => {
  259. this.handleChangeLoading("sCreateReply", false);
  260. });
  261. }
  262. /**
  263. * 删除回复
  264. * @param {*} replyId
  265. * @param {*} commentId
  266. */
  267. sDeleteReply(replyId, commentId) {
  268. this.handleChangeLoading("sDeleteReply", true);
  269. const { API } = this.props;
  270. this.axios(`${API}/replies/${replyId}?CommentID=${commentId}`, {
  271. method: "delete",
  272. withCredentials: true
  273. })
  274. .then(() => {
  275. const list = this.state.list.map(item => {
  276. if (item.id === commentId) {
  277. const replies = item.replies.filter(item => item.id !== replyId);
  278. item.replies = replies;
  279. item.reply_count -= 1;
  280. }
  281. return item;
  282. });
  283. this.setState({ list });
  284. this.props.onDelete(COMMENT_TYPE.REPLY);
  285. })
  286. .catch(this.errorHandler)
  287. .finally(() => {
  288. this.handleChangeLoading("sDeleteReply", false);
  289. });
  290. }
  291. /**
  292. * 评论 点赞/取消点赞
  293. * @param {string} commentId { commentId }
  294. * @param {boolean} favored 是否已经点过赞
  295. */
  296. sCommentFavor(commentId, favored) {
  297. this.handleChangeLoading("sCommentFavor", true);
  298. const { API } = this.props;
  299. this.axios(`${API}/comments/${commentId}/favor`, {
  300. method: favored ? "delete" : "put",
  301. withCredentials: true
  302. })
  303. .then(response => {
  304. if (this.props.showAlertFavor) {
  305. message.success(favored ? "取消点赞成功!" : "点赞成功!");
  306. }
  307. // 更新 list 中的该项数据的 favored
  308. const list = this.state.list.map(item => {
  309. if (item.id === commentId) {
  310. item.favored = !favored;
  311. item.favor_count += favored ? -1 : 1;
  312. }
  313. return item;
  314. });
  315. this.setState({ list });
  316. })
  317. .catch(this.errorHandler)
  318. .finally(() => {
  319. this.handleChangeLoading("sCommentFavor", false);
  320. });
  321. }
  322. /**
  323. * 回复 点赞/取消点赞
  324. * @param {string} replyId replyId
  325. * @param {string} commentId commentId
  326. * @param {boolean} favored 是否已经点过赞
  327. */
  328. sReplyFavor(replyId, commentId, favored) {
  329. this.handleChangeLoading("sReplyFavor", true);
  330. const { API } = this.props;
  331. this.axios(`${API}/replies/${replyId}/favor`, {
  332. method: favored ? "delete" : "put",
  333. data: {
  334. comment_id: commentId
  335. },
  336. withCredentials: true
  337. })
  338. .then(response => {
  339. message.success(favored ? "取消点赞成功!" : "点赞成功!");
  340. // 更新 list 中的该项数据的 favored
  341. const list = this.state.list.map(item => {
  342. if (item.id === commentId) {
  343. item.replies = item.replies.map(r => {
  344. if (r.id === replyId) {
  345. r.favored = !favored;
  346. // r.favor_count = response.data.favor_count;
  347. // 点赞数 +1,而不是使用后端返回的点赞数
  348. // 不然如果返回的不是增加 1,用户可能以为程序错误
  349. r.favor_count += favored ? -1 : 1;
  350. }
  351. return r;
  352. });
  353. }
  354. return item;
  355. });
  356. this.setState({ list });
  357. })
  358. .catch(this.errorHandler)
  359. .finally(() => {
  360. this.handleChangeLoading("sReplyFavor", false);
  361. });
  362. }
  363. /**
  364. * 获取 OSS 上传的参数
  365. */
  366. sOssSts() {
  367. this.handleChangeLoading("sOssSts", true);
  368. const { API } = this.props;
  369. this.axios
  370. .get(`${API}/oss/sts`)
  371. .then(response => {
  372. this.setState({ oss: { ...response.data } });
  373. })
  374. .catch(this.errorHandler)
  375. .finally(() => {
  376. this.handleChangeLoading("sOssSts", false);
  377. });
  378. }
  379. render() {
  380. // 添加到 Context 的数据
  381. const value = {
  382. ...this.state,
  383. ...this.props,
  384. sCreateComment: this.sCreateComment,
  385. sGetComment: this.sGetComment,
  386. sCommentFavor: this.sCommentFavor,
  387. sReplyFavor: this.sReplyFavor,
  388. sCreateReply: this.sCreateReply,
  389. sGetReply: this.sGetReply,
  390. sOssSts: this.sOssSts,
  391. sDeleteComment: this.sDeleteComment,
  392. sDeleteReply: this.sDeleteReply
  393. };
  394. return (
  395. <CommentContext.Provider value={value}>
  396. <div className="comment">
  397. {this.props.showEditor && (
  398. <CommentInput content={this.props.children} />
  399. )}
  400. {this.props.showList && (
  401. <div style={{ marginTop: 20 }}>
  402. <CommentList />
  403. </div>
  404. )}
  405. </div>
  406. </CommentContext.Provider>
  407. );
  408. }
  409. }
  410. App.propTypes = {
  411. type: PropTypes.number.isRequired, // 评论的 type
  412. businessId: PropTypes.string.isRequired, // 评论的 business_id
  413. API: PropTypes.string, // 评论的 API 前缀
  414. showList: PropTypes.bool, // 是否显示评论列表
  415. showEditor: PropTypes.bool, // 是否显示评论输入框
  416. showAlertComment: PropTypes.bool, // 评论成功之后,是否通过 Antd 的 Message 组件进行提示
  417. showAlertReply: PropTypes.bool, // 回复成功之后,是否通过 Antd 的 Message 组件进行提示
  418. showAlertFavor: PropTypes.bool, // 点赞/取消点赞成功之后,是否通过 Antd 的 Message 组件进行提示
  419. showError: PropTypes.bool, // 是否使用Antd的Message组件提示错误信息
  420. onError: PropTypes.func, // 错误回调, 出错了会被调用
  421. userId: PropTypes.number, // 用户id, comment内部不维护用户id, 调用组件时传递过来, 目前用于判断是否显示删除按钮
  422. pageType: PropTypes.string, // 分页类型
  423. page: PropTypes.number, // 页码
  424. onPageChange: PropTypes.func, // 页码变化回调
  425. onDelete: PropTypes.func
  426. };
  427. App.defaultProps = {
  428. API: "//api.links123.net/comment/v1",
  429. showList: true,
  430. showEditor: true,
  431. showAlertComment: false,
  432. showAlertReply: false,
  433. showAlertFavor: false,
  434. showError: true,
  435. pageType: "more",
  436. onPageChange: page => {},
  437. onDelete: () => {}
  438. };
  439. export { Editor, RenderText };
  440. export default App;