通用评论

App.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. 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. if (this.props.showAlertComment) {
  166. message.success("评论成功!");
  167. }
  168. if (isFunction(cb)) cb();
  169. // 将数据写入到 list 中
  170. // 临时插入
  171. // 等到获取数据之后,删除临时数据
  172. const { list, total } = this.state;
  173. list.unshift({
  174. ...response.data,
  175. isTemporary: true // 临时的数据
  176. });
  177. this.setState({ list, total: total + 1 });
  178. })
  179. .catch(error => {
  180. if (error.response && error.response.data && error.response.data.msg) {
  181. message.error(lang[error.response.data.msg] || ERROR_DEFAULT);
  182. return;
  183. }
  184. message.error(lang[error.message] || ERROR_DEFAULT);
  185. })
  186. .finally(() => {
  187. this.handleChangeLoading("sCreateComment", false);
  188. });
  189. }
  190. /**
  191. * 添加回复
  192. * 回复评论/回复回复
  193. * @param {object} data { comment_id, content, [reply_id] }
  194. */
  195. sCreateReply(data, cb) {
  196. if (!data.content) return message.error("回复内容不能为空 ");
  197. this.handleChangeLoading("sCreateReply", true);
  198. const { API } = this.props;
  199. this.axios(`${API}/replies`, {
  200. method: "post",
  201. data,
  202. withCredentials: true
  203. })
  204. .then(response => {
  205. if (this.props.showAlertReply) {
  206. message.success("回复成功!");
  207. }
  208. if (isFunction(cb)) cb();
  209. // 将数据写入到 list 中
  210. // 临时插入
  211. // 等到获取数据之后,删除临时数据
  212. const list = this.state.list.map(item => {
  213. if (item.id === data.comment_id) {
  214. if (!item.replies) item.replies = [];
  215. item.replies.push({
  216. ...response.data,
  217. isTemporary: true // 临时的数据
  218. });
  219. item.reply_count += 1;
  220. }
  221. return item;
  222. });
  223. this.setState({ list });
  224. })
  225. .catch(error => {
  226. if (error.response && error.response.data && error.response.data.msg) {
  227. message.error(lang[error.response.data.msg] || ERROR_DEFAULT);
  228. return;
  229. }
  230. message.error(lang[error.message] || ERROR_DEFAULT);
  231. })
  232. .finally(() => {
  233. this.handleChangeLoading("sCreateReply", false);
  234. });
  235. }
  236. /**
  237. * 评论 点赞/取消点赞
  238. * @param {string} commentId { commentId }
  239. * @param {boolean} favored 是否已经点过赞
  240. */
  241. sCommentFavor(commentId, favored) {
  242. this.handleChangeLoading("sCommentFavor", true);
  243. const { API } = this.props;
  244. this.axios(`${API}/comments/${commentId}/favor`, {
  245. method: favored ? "delete" : "put",
  246. withCredentials: true
  247. })
  248. .then(response => {
  249. if (this.props.showAlertFavor) {
  250. message.success(favored ? "取消点赞成功!" : "点赞成功!");
  251. }
  252. // 更新 list 中的该项数据的 favored
  253. const list = this.state.list.map(item => {
  254. if (item.id === commentId) {
  255. item.favored = !favored;
  256. item.favor_count += favored ? -1 : 1;
  257. }
  258. return item;
  259. });
  260. this.setState({ list });
  261. })
  262. .catch(error => {
  263. if (error.response && error.response.data && error.response.data.msg) {
  264. message.error(lang[error.response.data.msg] || ERROR_DEFAULT);
  265. return;
  266. }
  267. message.error(lang[error.message] || ERROR_DEFAULT);
  268. })
  269. .finally(() => {
  270. this.handleChangeLoading("sCommentFavor", false);
  271. });
  272. }
  273. /**
  274. * 回复 点赞/取消点赞
  275. * @param {string} replyId replyId
  276. * @param {string} commentId commentId
  277. * @param {boolean} favored 是否已经点过赞
  278. */
  279. sReplyFavor(replyId, commentId, favored) {
  280. this.handleChangeLoading("sReplyFavor", true);
  281. const { API } = this.props;
  282. this.axios(`${API}/replies/${replyId}/favor`, {
  283. method: favored ? "delete" : "put",
  284. data: {
  285. comment_id: commentId
  286. },
  287. withCredentials: true
  288. })
  289. .then(response => {
  290. message.success(favored ? "取消点赞成功!" : "点赞成功!");
  291. // 更新 list 中的该项数据的 favored
  292. const list = this.state.list.map(item => {
  293. if (item.id === commentId) {
  294. item.replies = item.replies.map(r => {
  295. if (r.id === replyId) {
  296. r.favored = !favored;
  297. // r.favor_count = response.data.favor_count;
  298. // 点赞数 +1,而不是使用后端返回的点赞数
  299. // 不然如果返回的不是增加 1,用户可能以为程序错误
  300. r.favor_count += favored ? -1 : 1;
  301. }
  302. return r;
  303. });
  304. }
  305. return item;
  306. });
  307. this.setState({ list });
  308. })
  309. .catch(error => {
  310. if (error.response && error.response.data && error.response.data.msg) {
  311. message.error(lang[error.response.data.msg] || ERROR_DEFAULT);
  312. return;
  313. }
  314. message.error(lang[error.message] || ERROR_DEFAULT);
  315. })
  316. .finally(() => {
  317. this.handleChangeLoading("sReplyFavor", false);
  318. });
  319. }
  320. /**
  321. * 获取 OSS 上传的参数
  322. */
  323. sOssSts() {
  324. this.handleChangeLoading("sOssSts", true);
  325. const { API } = this.props;
  326. this.axios
  327. .get(`${API}/oss/sts`)
  328. .then(response => {
  329. this.setState({ oss: { ...response.data } });
  330. })
  331. .catch(error => {
  332. if (error.response && error.response.data && error.response.data.msg) {
  333. message.error(lang[error.response.data.msg] || ERROR_DEFAULT);
  334. return;
  335. }
  336. message.error(lang[error.message] || ERROR_DEFAULT);
  337. })
  338. .finally(() => {
  339. this.handleChangeLoading("sOssSts", false);
  340. });
  341. }
  342. render() {
  343. // 添加到 Context 的数据
  344. const value = {
  345. ...this.state,
  346. ...this.props,
  347. sCreateComment: this.sCreateComment,
  348. sGetComment: this.sGetComment,
  349. sCommentFavor: this.sCommentFavor,
  350. sReplyFavor: this.sReplyFavor,
  351. sCreateReply: this.sCreateReply,
  352. sGetReply: this.sGetReply,
  353. sOssSts: this.sOssSts
  354. };
  355. return (
  356. <CommentContext.Provider value={value}>
  357. <div className="comment">
  358. {this.props.showEditor && (
  359. <CommentInput content={this.props.children} />
  360. )}
  361. {this.props.showList && (
  362. <div style={{ marginTop: 20 }}>
  363. <CommentList />
  364. </div>
  365. )}
  366. </div>
  367. </CommentContext.Provider>
  368. );
  369. }
  370. }
  371. App.propTypes = {
  372. type: PropTypes.number.isRequired, // 评论的 type
  373. businessId: PropTypes.string.isRequired, // 评论的 business_id
  374. API: PropTypes.string, // 评论的 API 前缀
  375. showList: PropTypes.bool, // 是否显示评论列表
  376. showEditor: PropTypes.bool, // 是否显示评论输入框
  377. showAlertComment: PropTypes.bool, // 评论成功之后,是否通过 Antd 的 Message 组件进行提示
  378. showAlertReply: PropTypes.bool, // 回复成功之后,是否通过 Antd 的 Message 组件进行提示
  379. showAlertFavor: PropTypes.bool // 点赞/取消点赞成功之后,是否通过 Antd 的 Message 组件进行提示
  380. };
  381. App.defaultProps = {
  382. API: "http://api.links123.net/comment/v1",
  383. showList: true,
  384. showEditor: true,
  385. showAlertComment: false,
  386. showAlertReply: false,
  387. showAlertFavor: false
  388. };
  389. export { Editor, RenderText };
  390. export default App;