JavaScript无法在VSCode中格式化吗?

时间:2019-08-13 15:46:35

标签: javascript reactjs visual-studio-code

几天前,我的某些文件停止使用空格,缩进等格式设置。

例如,现在我的减速器正在工作(即使customerWithReview函数中出现流错误:

reducer.js

// @flow
import type {
  CustomerAction,
  CustomerState,
  CustomerCollection
} from "../CustomerTypes";

import Customer from "../../models/Customer";
import Review from "../../models/Review";

const logActionTypes = action =>
  action.type[0] !== "@" && console.log("CustomerReducer:", action.type);

const initialState: CustomerState = {
  customers: null,
  newItem: null,
  searchResults: null,
  error: null,
  isLoading: false
};

export default function customerReducer(
  state: CustomerState = initialState,
  action: CustomerAction
) {
  let customers: CustomerCollection;
  switch (action.type) {
    case "GET_CUSTOMERS_SUCCESS":
      return { ...state, customers: action.customers, isLoading: false };
    case "GET_CUSTOMERS_FAILURE":
      return { ...state, error: action.error, isLoading: false };
    case "NEW_CUSTOMER_START":
    case "CUSTOMER_ADD_REVIEW_START":
      return { ...state, newItem: null, error: null, isLoading: true };
    case "NEW_CUSTOMER_SUCCESS":
      customers = {
        ...state.customers,
        [action.customer.id]: action.customer
      };
      return {
        ...state,
        customers,
        newItem: action.customer,
        isLoading: false
      };
    case "CUSTOMER_SEARCH_SUCCESS":
      return { ...state, searchResults: action.results, isLoading: false };
    case "CUSTOMER_ADD_REVIEW_SUCCESS":
      const newCustomer = customerWithReview(action.review);
      customers = {
        ...state.customers,
        [action.review.customerId]: newCustomer
      };
      // debugger;
      return {
        ...state,
        customers,
        newItem: newCustomer,
        isLoading: false
      };
    case "NEW_CUSTOMER_FAILURE":
    case "CUSTOMER_SEARCH_FAILURE":
    case "CUSTOMER_ADD_REVIEW_FAILURE":
      console.log("from reducer:", action.error);
      return {
        ...state,
        newItem: null,
        error: action.error,
        isLoading: false
      };
    default:
      return state;
  }

  function customerWithReview(review: Review): Customer {
    const id: number = review.customerId;
    const oldCustomer = state.customers[id];
    const newReviews = [review, ...oldCustomer.reviews];
    const newCustomer = new Customer({ ...oldCustomer, reviews: newReviews });
    return newCustomer;
  }
}

但是该组件文件(无错误)不会格式化。请注意formProps函数内部render属性中的间距。

CustomerScreen.js

// @flow
import React, { Component } from "react";
import { connect } from "react-redux";
import {
  StyleSheet,
  ScrollView,
  View,
  KeyboardAvoidingView
} from "react-native";
import {
  ThemeProvider,
  Text,
  Divider,
  Rating,
  Button
} from "react-native-elements";
import Customer from "../models/Customer";
import Review from "../models/Review";
import User from "../models/User";
import ReviewView from "../subviews/ReviewView";
import ReviewsList from "../subviews/ReviewsList";
import NewReviewScreen from "./NewReviewScreen";
import { addNewReview } from "../redux/action-creators/customerActionCreators";
import * as Types from "../redux/CustomerTypes"

type Props = { customer: Customer,
  addNewReview: function, allCustomers: Types.CustomerCollection, user: User, isLoading: boolean, newReview: Review
 };
type State = { isReviewing: boolean, isLoading: boolean };

export class CustomerScreen extends Component<Props, State> {
  state = { isReviewing: false, isLoading: false };

  automate = async() => await setTimeout(this.startReview.bind(this), 10)

  // componentDidMount = () => this.automate()

  createReview({ content, rating }: Review) {
    const review = {
      customerId: this.props.customer.id, userId: this.props.user.id, content, rating,
      userId: 8
    }
    this.props.addNewReview(review);
    // this.setState({ isReviewing: false });
  }

  startReview = () => this.setState({ isReviewing: true })
  cancelReview = () => this.setState({ isReviewing: false })
  get showReview(): boolean { return this.state.isReviewing || !!this.props.newReview }

  render() {
    // const customer = this.props.customer // provided by container
    const customer = this.props.allCustomers[this.props.customer.id]
    const listProps = {customer, onStartReviewPress: this.startReview.bind(this)}
    const formProps = {                onCancel: this.cancelReview.bind(this),
                onSubmit:this.createReview.bind(this),
                isLoading:this.props.isLoading
}
    return (
      <ThemeProvider theme={theme}>
        <KeyboardAvoidingView
          style={styles.container}
          enabled
          behavior="position"
        >
          <ScrollView contentContainerStyle={styles.scrollView}>
            <CustomerInfo customer={customer} />
            {!this.showReview ? (
              <Reviews {...listProps}/>
            ) : (
              <NewReviewScreen
                onCancel={this.cancelReview.bind(this)}
                onSubmit={this.createReview.bind(this)}
                isLoading={this.props.isLoading}
              />
            )}
            <Divider style={{ height: 100 }} />
          </ScrollView>
        </KeyboardAvoidingView>
      </ThemeProvider>
    );
  }
}

export default connect(
  ({ customerReducer, authReducer }) => ({
    allCustomers: customerReducer.customers,
    user: authReducer.user.user,
    isLoading: customerReducer.isLoading,
    newReview: customerReducer.newItem
  }),
  { addNewReview }
)(CustomerScreen);

const CustomerInfo = ({ customer }) => {
  return (
    <View>
      <Text h1>{customer.name}</Text>
      <Text style={styles.detailText}>{customer.address}</Text>
      <Text style={styles.customerDescription}>{customer.description}</Text>
      {customer.reviews.length > 0 && (
        <View>
          <Text style={styles.detailText}>
            Rating ({customer.reviews.length} reviews):
          </Text>
          <Rating
            readonly
            startingValue={customer.averageRating}
            style={styles.rating}
            imageSize={20}
          />
        </View>
      )}
    </View>
  );
};

type ReviewsProps = {}

const Reviews = props => 
  <View style={{ width: "100%" }}>
    <ReviewsList
      customer={props.customer}
      onStartReviewPress={props.onStartReviewPress}
    />
  </View>

const styles = {
  scrollView: {
    margin: 20,
    marginBottom: 100,
    justifyContent: "flex-start",
    alignItems: "flex-start",
  },
  container:{},
  divider: {
    backgroundColor: "black",
    height: 50
  },
  detailText: { paddingTop: 5 },
  customerDescription: { marginTop: 25, textAlign:"center" },
  rating: { padding: 5, alignItems: "flex-start" }
};

const theme = {
  Text: {
    style: { fontSize: 18 }
  }
};

根据要求,我要添加我的软件包和设置。我不会删除代码,因为一个文件有效而另一个文件无效,所以我很想解释为什么会发生这种情况。

package.json

{
  "name": "QMGProzReviewsNative",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.6.1",
    "axios": "^0.19.0",
    "axios-mock-adapter": "^1.17.0",
    "email-validator": "^2.0.4",
    "lodash": "^4.17.15",
    "react": "16.8.6",
    "react-dom": "^16.8.6",
    "react-native": "0.60.4",
    "react-native-elements": "^1.1.0",
    "react-native-gesture-handler": "^1.3.0",
    "react-native-indicators": "^0.13.0",
    "react-native-vector-icons": "^6.6.0",
    "react-navigation": "^3.11.0",
    "react-redux": "^7.0.3",
    "redux": "^4.0.1",
    "redux-saga": "^1.0.3",
    "sugar": "^2.0.6"
  },
  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/runtime": "^7.5.5",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.8.0",
    "eslint": "^6.1.0",
    "flow-bin": "^0.104.0",
    "flow-typed": "^2.6.0",
    "jest": "^24.8.0",
    "jest-mock-axios": "^3.0.0",
    "metro-react-native-babel-preset": "^0.55.0",
    "prettier-eslint": "^8.8.2",
    "react-test-renderer": "16.8.6",
    "redux-saga-tester": "^1.0.468"
  },
  "jest": {
    "preset": "react-native"
  }
}

settings.json(工作场所)

{
  "javascript.validate.enable": false,
  "prettier.eslintIntegration": true,
  "editor.formatOnSave": true
}

用户设置

{
  "window.zoomLevel": -1,
  "editor.fontSize": 14,
  "javascript.updateImportsOnFileMove.enabled": "never",
  "git.enableSmartCommit": true,
  "git.confirmSync": false,
  "editor.wordWrap": "on",
  "workbench.colorCustomizations": {
    "editorError.foreground": "#ff5100",
    "editorWarning.foreground": "#45bd0000",
    "editorInfo.foreground": "#00000000"
  },
  "explorer.confirmDelete": false,
  "editor.tabSize": 2,
  "editor.multiCursorModifier": "ctrlCmd",
  "editor.showFoldingControls": "always",
  "editor.tabCompletion": "onlySnippets",
  "editor.formatOnPaste": true,
  "breadcrumbs.enabled": true,
  "editor.quickSuggestions": {
    // "other": false
  },
  "editor.wordBasedSuggestions": true,
  "explorer.confirmDragAndDrop": false,
  "editor.snippetSuggestions": "top",
  "terminal.integrated.fontSize": 15,
  "workbench.startupEditor": "newUntitledFile",
  "workbench.editor.showTabs": false,
  "terminal.integrated.macOptionClickForcesSelection": true,
  "markdown.preview.fontSize": 18,
  "emmet.includeLanguages": {
    "html": "html",
    "erb": "html",
    "js": "javascript-react"
  },
  "editor.parameterHints.cycle": true,
  "editor.occurrencesHighlight": false,
  "editor.minimap.enabled": false,
  "editor.renderIndentGuides": false,
  "editor.detectIndentation": false,
  "diffEditor.ignoreTrimWhitespace": true,
  "diffEditor.renderSideBySide": false,
  "zenMode.hideLineNumbers": false,
  "git.autofetch": true,
  "csv-preview.theme": "cerulean",
  "mocha.files.glob": "spec/**/*.js",
  "debug.toolBarLocation": "docked",
  "debug.inlineValues": true,
  "debug.allowBreakpointsEverywhere": true,
  "sync.gist": "2836d619beeccd77b4fffb43ad0a3495",
  "debug.console.fontSize": 14,
  "debug.internalConsoleOptions": "openOnSessionStart",
  "editor.fontFamily": "Monaco, 'Courier New', monospace",
  "python.jediEnabled": false,
  "react-native.packager.port": 19005,
  "[javascriptreact]": {},
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "editor.formatOnSave": true,
  "flow.useNPMPackagedFlow": true,
  "[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "prettier.eslintIntegration": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.foldingStrategy": "indentation",
  "editor.suggest.localityBonus": true,
  "editor.suggest.shareSuggestSelections": true,
  "editor.suggest.snippetsPreventQuickSuggestions": false,
  "javascript.suggest.completeFunctionCalls": true,
  "workbench.activityBar.visible": false,
  "editor.suggestSelection": "first",
  "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue"
}

1 个答案:

答案 0 :(得分:0)

使用Ctrl + k,Ctrl + F并使用任何代码格式扩展名(例如,更漂亮)。