簡體   English   中英

為什么我每次運行 react-app 都必須清除緩存

[英]why i have to clear cache everytime running react-app

我目前正在為我在大學的期末項目學習 react,我遇到了一些我不知道是否正常的問題。

錯誤是:

Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at Module../src/redux/reducers/loginReducer.js (loginReducer.js:3)
at __webpack_require__ (bootstrap:784)
at fn (bootstrap:150)
at Module../src/redux/reducers/rootReducer.js (rootReducer.js:1)
at __webpack_require__ (bootstrap:784)
at fn (bootstrap:150)
at Module../src/index.js (config.js:1)
at __webpack_require__ (bootstrap:784)
at fn (bootstrap:150)
at Object.1 (types.js:1)
at __webpack_require__ (bootstrap:784)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback [as push] (bootstrap:32)
at main.chunk.js:1

顯然,這個解決方案我只需要在每次啟動反應應用程序時清除緩存。 這是正常的事情嗎? 恐怕當我將該網站上線時,用戶將無法訪問它。 或者它只會在本地主機上這樣?? webpack 與此有什么關系?

提前致謝,這是我第一次在這里提問。

((EDIT 1)) 這是錯誤中提到的代碼

(登錄Reducer.js)

import { userConstants } from '../types';

let user = JSON.parse(localStorage.getItem('user'));
const initialState = user ? 
    { loggedIn: true, user } : {};

export function authentication(state = initialState, action) {
  switch (action.type) {
    case userConstants.LOGIN_REQUEST:
      return {
        loggingIn: true,//state yang dikirim ke global, bisa diganti jg di reducer kalo dibutuhin di component lain
      };
    case userConstants.LOGIN_SUCCESS:
      return {
        loggedIn:true,
        user: action.user
      };
    case userConstants.LOGIN_FAILURE:
      return {};
    case userConstants.LOGOUT:
      return {};
    default:
      return state
  }
}

(rootReducer.js)

import {combineReducers} from 'redux';

//reducers
import {authentication} from './loginReducer';
import {register} from './registerReducer';


export const rootReducer = combineReducers({
    authentication,
    register
  });

(索引.js)

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import {rootReducer} from './redux/reducers/rootReducer';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';

const loggerMiddleware = createLogger();

//store
const store = createStore(rootReducer,
    applyMiddleware(
        thunkMiddleware,
        loggerMiddleware
    ));

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('app'));

這里https://github.com/facebook/create-react-app/issues/7261有多種解決方案可以解決您的問題,其中一個可能對您有用,其他地方的人也建議這樣做:從 C 中刪除所有內容: \\Users\\username\\AppData\\Roaming\\npm-cache修復了問題

編輯:看起來你正在嘗試對無效的 JSON 格式執行JSON.parse ,你能檢查一下localStorage.getItem('user')里面有什么嗎? 它可能是空字符串並導致JSON.parse使您的代碼崩潰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM