通用评论

App.js 12KB

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