makeNoMethodSetStateRule.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * @fileoverview Prevent usage of setState in lifecycle methods
  3. * @author Yannick Croissant
  4. */
  5. 'use strict';
  6. const docsUrl = require('./docsUrl');
  7. // ------------------------------------------------------------------------------
  8. // Rule Definition
  9. // ------------------------------------------------------------------------------
  10. function makeNoMethodSetStateRule(methodName) {
  11. return {
  12. meta: {
  13. docs: {
  14. description: `Prevent usage of setState in ${methodName}`,
  15. category: 'Best Practices',
  16. recommended: false,
  17. url: docsUrl(methodName)
  18. },
  19. schema: [{
  20. enum: ['disallow-in-func']
  21. }]
  22. },
  23. create: function(context) {
  24. const mode = context.options[0] || 'allow-in-func';
  25. // --------------------------------------------------------------------------
  26. // Public
  27. // --------------------------------------------------------------------------
  28. return {
  29. CallExpression: function(node) {
  30. const callee = node.callee;
  31. if (
  32. callee.type !== 'MemberExpression' ||
  33. callee.object.type !== 'ThisExpression' ||
  34. callee.property.name !== 'setState'
  35. ) {
  36. return;
  37. }
  38. const ancestors = context.getAncestors(callee).reverse();
  39. let depth = 0;
  40. for (let i = 0, j = ancestors.length; i < j; i++) {
  41. if (/Function(Expression|Declaration)$/.test(ancestors[i].type)) {
  42. depth++;
  43. }
  44. if (
  45. (ancestors[i].type !== 'Property' && ancestors[i].type !== 'MethodDefinition') ||
  46. ancestors[i].key.name !== methodName ||
  47. (mode !== 'disallow-in-func' && depth > 1)
  48. ) {
  49. continue;
  50. }
  51. context.report({
  52. node: callee,
  53. message: `Do not use setState in ${methodName}`
  54. });
  55. break;
  56. }
  57. }
  58. };
  59. }
  60. };
  61. }
  62. module.exports = makeNoMethodSetStateRule;