通用评论

App.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 } 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. })
  216. .catch(this.errorHandler)
  217. .finally(() => {
  218. this.handleChangeLoading("sDeleteComment", false);
  219. });
  220. }
  221. /**
  222. * 添加回复
  223. * 回复评论/回复回复
  224. * @param {object} data { comment_id, content, [reply_id] }
  225. */
  226. sCreateReply(data, cb) {
  227. if (!data.content) return this.error("回复内容不能为空 ");
  228. this.handleChangeLoading("sCreateReply", true);
  229. const { API } = this.props;
  230. this.axios(`${API}/replies`, {
  231. method: "post",
  232. data,
  233. withCredentials: true
  234. })
  235. .then(response => {
  236. if (this.props.showAlertReply) {
  237. message.success("回复成功!");
  238. }
  239. if (isFunction(cb)) cb();
  240. // 将数据写入到 list 中
  241. // 临时插入
  242. // 等到获取数据之后,删除临时数据
  243. const list = this.state.list.map(item => {
  244. if (item.id === data.comment_id) {
  245. if (!item.replies) item.replies = [];
  246. item.replies.push({
  247. ...response.data,
  248. isTemporary: true // 临时的数据
  249. });
  250. item.reply_count += 1;
  251. }
  252. return item;
  253. });
  254. this.setState({ list });
  255. })
  256. .catch(this.errorHandler)
  257. .finally(() => {
  258. this.handleChangeLoading("sCreateReply", false);
  259. });
  260. }
  261. /**
  262. * 删除回复
  263. * @param {*} replyId
  264. * @param {*} commentId
  265. */
  266. sDeleteReply(replyId, commentId) {
  267. this.handleChangeLoading("sDeleteReply", true);
  268. const { API } = this.props;
  269. this.axios(`${API}/replies/${replyId}?CommentID=${commentId}`, {
  270. method: "delete",
  271. withCredentials: true
  272. })
  273. .then(() => {
  274. const list = this.state.list.map(item => {
  275. if (item.id === commentId) {
  276. const replies = item.replies.filter(item => item.id !== replyId);
  277. item.replies = replies;
  278. item.reply_count -= 1;
  279. }
  280. return item;
  281. });
  282. this.setState({ list });
  283. })
  284. .catch(this.errorHandler)
  285. .finally(() => {
  286. this.handleChangeLoading("sDeleteReply", false);
  287. });
  288. }
  289. /**
  290. * 评论 点赞/取消点赞
  291. * @param {string} commentId { commentId }
  292. * @param {boolean} favored 是否已经点过赞
  293. */
  294. sCommentFavor(commentId, favored) {
  295. this.handleChangeLoading("sCommentFavor", true);
  296. const { API } = this.props;
  297. this.axios(`${API}/comments/${commentId}/favor`, {
  298. method: favored ? "delete" : "put",
  299. withCredentials: true
  300. })
  301. .then(response => {
  302. if (this.props.showAlertFavor) {
  303. message.success(favored ? "取消点赞成功!" : "点赞成功!");
  304. }
  305. // 更新 list 中的该项数据的 favored
  306. const list = this.state.list.map(item => {
  307. if (item.id === commentId) {
  308. item.favored = !favored;
  309. item.favor_count += favored ? -1 : 1;
  310. }
  311. return item;
  312. });
  313. this.setState({ list });
  314. })
  315. .catch(this.errorHandler)
  316. .finally(() => {
  317. this.handleChangeLoading("sCommentFavor", false);
  318. });
  319. }
  320. /**
  321. * 回复 点赞/取消点赞
  322. * @param {string} replyId replyId
  323. * @param {string} commentId commentId
  324. * @param {boolean} favored 是否已经点过赞
  325. */
  326. sReplyFavor(replyId, commentId, favored) {
  327. this.handleChangeLoading("sReplyFavor", true);
  328. const { API } = this.props;
  329. this.axios(`${API}/replies/${replyId}/favor`, {
  330. method: favored ? "delete" : "put",
  331. data: {
  332. comment_id: commentId
  333. },
  334. withCredentials: true
  335. })
  336. .then(response => {
  337. message.success(favored ? "取消点赞成功!" : "点赞成功!");
  338. // 更新 list 中的该项数据的 favored
  339. const list = this.state.list.map(item => {
  340. if (item.id === commentId) {
  341. item.replies = item.replies.map(r => {
  342. if (r.id === replyId) {
  343. r.favored = !favored;
  344. // r.favor_count = response.data.favor_count;
  345. // 点赞数 +1,而不是使用后端返回的点赞数
  346. // 不然如果返回的不是增加 1,用户可能以为程序错误
  347. r.favor_count += favored ? -1 : 1;
  348. }
  349. return r;
  350. });
  351. }
  352. return item;
  353. });
  354. this.setState({ list });
  355. })
  356. .catch(this.errorHandler)
  357. .finally(() => {
  358. this.handleChangeLoading("sReplyFavor", false);
  359. });
  360. }
  361. /**
  362. * 获取 OSS 上传的参数
  363. */
  364. sOssSts() {
  365. this.handleChangeLoading("sOssSts", true);
  366. const { API } = this.props;
  367. this.axios
  368. .get(`${API}/oss/sts`)
  369. .then(response => {
  370. this.setState({ oss: { ...response.data } });
  371. })
  372. .catch(this.errorHandler)
  373. .finally(() => {
  374. this.handleChangeLoading("sOssSts", false);
  375. });
  376. }
  377. render() {
  378. // 添加到 Context 的数据
  379. const value = {
  380. ...this.state,
  381. ...this.props,
  382. sCreateComment: this.sCreateComment,
  383. sGetComment: this.sGetComment,
  384. sCommentFavor: this.sCommentFavor,
  385. sReplyFavor: this.sReplyFavor,
  386. sCreateReply: this.sCreateReply,
  387. sGetReply: this.sGetReply,
  388. sOssSts: this.sOssSts,
  389. sDeleteComment: this.sDeleteComment,
  390. sDeleteReply: this.sDeleteReply
  391. };
  392. return (
  393. <CommentContext.Provider value={value}>
  394. <div className="comment">
  395. {this.props.showEditor && (
  396. <CommentInput content={this.props.children} />
  397. )}
  398. {this.props.showList && (
  399. <div style={{ marginTop: 20 }}>
  400. <CommentList />
  401. </div>
  402. )}
  403. </div>
  404. </CommentContext.Provider>
  405. );
  406. }
  407. }
  408. App.propTypes = {
  409. type: PropTypes.number.isRequired, // 评论的 type
  410. businessId: PropTypes.string.isRequired, // 评论的 business_id
  411. API: PropTypes.string, // 评论的 API 前缀
  412. showList: PropTypes.bool, // 是否显示评论列表
  413. showEditor: PropTypes.bool, // 是否显示评论输入框
  414. showAlertComment: PropTypes.bool, // 评论成功之后,是否通过 Antd 的 Message 组件进行提示
  415. showAlertReply: PropTypes.bool, // 回复成功之后,是否通过 Antd 的 Message 组件进行提示
  416. showAlertFavor: PropTypes.bool, // 点赞/取消点赞成功之后,是否通过 Antd 的 Message 组件进行提示
  417. showError: PropTypes.bool, // 是否使用Antd的Message组件提示错误信息
  418. onError: PropTypes.func, // 错误回调, 出错了会被调用
  419. userId: PropTypes.number, // 用户id, comment内部不维护用户id, 调用组件时传递过来, 目前用于判断是否显示删除按钮
  420. pageType: PropTypes.string, // 分页类型
  421. page: PropTypes.number, // 页码
  422. onPageChange: PropTypes.func // 页码变化回调
  423. };
  424. App.defaultProps = {
  425. API: "//api.links123.net/comment/v1",
  426. showList: true,
  427. showEditor: true,
  428. showAlertComment: false,
  429. showAlertReply: false,
  430. showAlertFavor: false,
  431. showError: true,
  432. pageType: "more",
  433. onPageChange: page => {}
  434. };
  435. export { Editor, RenderText };
  436. export default App;