通用评论

App.js 12KB

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