通用评论

App.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 } = {}) {
  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. // 将数据写入到 list 中
  166. // 临时插入
  167. // 等到获取数据之后,删除临时数据
  168. const { list, total } = this.state;
  169. list.unshift({
  170. ...response.data,
  171. isTemporary: true // 临时的数据
  172. });
  173. this.setState({ list, total: total + 1 });
  174. })
  175. .catch(error => {
  176. if (error.response && error.response.data && error.response.data.msg) {
  177. message.error(lang[error.response.data.msg] || ERROR_DEFAULT);
  178. return;
  179. }
  180. message.error(lang[error.message] || ERROR_DEFAULT);
  181. })
  182. .finally(() => {
  183. this.handleChangeLoading("sCreateComment", false);
  184. });
  185. }
  186. /**
  187. * 添加回复
  188. * 回复评论/回复回复
  189. * @param {object} data { comment_id, content, [reply_id] }
  190. */
  191. sCreateReply(data, cb) {
  192. // console.log("list: ", this.state.list);
  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. console.log("replyId, commentId ", replyId, commentId);
  275. const { API } = this.props;
  276. this.axios(`${API}/replies/${replyId}/favor`, {
  277. method: favored ? "delete" : "put",
  278. daa: {
  279. comment_id: commentId
  280. },
  281. withCredentials: true
  282. })
  283. .then(response => {
  284. console.log("response: ", response);
  285. message.success(favored ? "取消点赞成功!" : "点赞成功!");
  286. // TODO: (2018.07.20 node) 对评论的回复点赞,报错
  287. // // 更新 list 中的该项数据的 favored
  288. // const list = this.state.list.map(item => {
  289. // if (item.id === replyId) {
  290. // item.favored = !favored;
  291. // item.favor_count += favored ? -1 : 1;
  292. // }
  293. // return item;
  294. // });
  295. // this.setState({ list });
  296. })
  297. .catch(error => {
  298. if (error.response && error.response.data && error.response.data.msg) {
  299. message.error(lang[error.response.data.msg] || ERROR_DEFAULT);
  300. return;
  301. }
  302. message.error(lang[error.message] || ERROR_DEFAULT);
  303. })
  304. .finally(() => {
  305. this.handleChangeLoading("sReplyFavor", false);
  306. });
  307. }
  308. /**
  309. * 获取 OSS 上传的参数
  310. */
  311. sOssSts() {
  312. this.handleChangeLoading("sOssSts", true);
  313. const { API } = this.props;
  314. this.axios
  315. .get(`${API}/oss/sts`)
  316. .then(response => {
  317. this.setState({ oss: { ...response.data } });
  318. })
  319. .catch(error => {
  320. if (error.response && error.response.data && error.response.data.msg) {
  321. message.error(lang[error.response.data.msg] || ERROR_DEFAULT);
  322. return;
  323. }
  324. message.error(lang[error.message] || ERROR_DEFAULT);
  325. })
  326. .finally(() => {
  327. this.handleChangeLoading("sOssSts", false);
  328. });
  329. }
  330. render() {
  331. // 添加到 Context 的数据
  332. const value = {
  333. ...this.state,
  334. ...this.props,
  335. sCreateComment: this.sCreateComment,
  336. sGetComment: this.sGetComment,
  337. sCommentFavor: this.sCommentFavor,
  338. sReplyFavor: this.sReplyFavor,
  339. sCreateReply: this.sCreateReply,
  340. sGetReply: this.sGetReply,
  341. sOssSts: this.sOssSts
  342. };
  343. return (
  344. <CommentContext.Provider value={value}>
  345. <div className="comment">
  346. {this.props.showHeader && (
  347. <div style={{ marginBottom: 15 }}>
  348. <Tag className="comment-header-tag">留言</Tag>
  349. <span className="comment-header-tip">口碑</span>
  350. <span className="comment-header-text">
  351. (全站挑出毛病或提出合理建议,奖励10到100元红包)
  352. </span>
  353. </div>
  354. )}
  355. {this.props.showEditor && (
  356. <CommentInput content={this.props.children} />
  357. )}
  358. {this.props.showList && (
  359. <div style={{ marginTop: 20 }}>
  360. <CommentList />
  361. </div>
  362. )}
  363. </div>
  364. </CommentContext.Provider>
  365. );
  366. }
  367. }
  368. App.propTypes = {
  369. type: PropTypes.number.isRequired, // 评论的 type
  370. businessId: PropTypes.string.isRequired, // 评论的 business_id
  371. API: PropTypes.string, // 评论的 API 前缀
  372. showList: PropTypes.bool, // 是否显示评论列表
  373. showEditor: PropTypes.bool, // 是否显示评论输入框
  374. showHeader: PropTypes.bool // 是否显示评论顶部的提示
  375. };
  376. App.defaultProps = {
  377. API: "http://api.links123.net/comment/v1",
  378. showList: true,
  379. showEditor: true,
  380. showHeader: true
  381. };
  382. export { Editor };
  383. export default App;