为什么 React/redux 状态会在刷新时重置?

2024-02-01

当我登录时,一切正常,但当我点击刷新或导航到其他地方时,状态就会重置。知道为什么吗?我希望能够从状态引用用户并获取名称等信息并在组件内使用它。但它只有在我登录后才起作用,然后它就会重置。

另外,为什么我必须在mapstatetoprops中使用.get?如果没有,我会得到一个 Map 对象。是因为IMMUTABLE.JS吗?

这是我的 app.js 文件

/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */

// Needed for redux-saga es6 generator support
import '@babel/polyfill';

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router/immutable';
import jwt_decode from 'jwt-decode';
import FontFaceObserver from 'fontfaceobserver';
import history from 'utils/history';
import 'sanitize.css/sanitize.css';

// Import root app
import App from 'containers/App';

import './styles/layout/base.scss';

// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';

import { setCurrentUser, logoutUser } from './redux/actions/authActions';
import setAuthToken from './utils/setAuthToken';

// Load the favicon and the .htaccess file
import '!file-loader?name=[name].[ext]!../public/favicons/favicon.ico'; // eslint-disable-line
import 'file-loader?name=.htaccess!./.htaccess'; // eslint-disable-line

import configureStore from './redux/configureStore';

// Import i18n messages
import { translationMessages } from './i18n';

// Check for token to keep user logged in
if (localStorage.jwtToken) {
  // Set auth token header auth
  const token = JSON.parse(localStorage.jwtToken);
  setAuthToken(token);

  // Decode token and get user info and exp
  const decoded = jwt_decode(token);
  console.log(decoded);

  // Set user and isAuthenticated
  setCurrentUser(decoded);
  // Check for expired token
  const currentTime = Date.now() / 1000; // to get in milliseconds
  if (decoded.exp < currentTime) {
    // Logout user
    logoutUser();

    // Redirect to login
    window.location.href = './';
  }
}

// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});

// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
  document.body.classList.add('fontLoaded');
});

// Create redux store with history
const initialState = {};
const store = configureStore(initialState, history);
const MOUNT_NODE = document.getElementById('app');

const render = messages => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={messages}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
      </LanguageProvider>
    </Provider>,
    MOUNT_NODE,
  );
};

if (module.hot) {
  // Hot reloadable React components and translation json files
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept(['./i18n', 'containers/App'], () => {
    ReactDOM.unmountComponentAtNode(MOUNT_NODE);
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  new Promise(resolve => {
    resolve(import('intl'));
  })
    .then(() =>
      Promise.all([import('intl/locale-data/jsonp/en.js'), import('intl/locale-data/jsonp/de.js')]),
    ) // eslint-disable-line prettier/prettier
    .then(() => render(translationMessages))
    .catch(err => {
      throw err;
    });
} else {
  render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
  require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}

app文件夹内的index.js

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import NotFound from 'containers/Pages/Standalone/NotFoundDedicated';
import Auth from './Auth';
import Application from './Application';
import ThemeWrapper, { AppContext } from './ThemeWrapper';
import { Login } from '../pageListAsync';
import PrivateRoute from './PrivateRoute';

const isLoggedIn = localStorage.getItem('jwtToken') !== null ? true : false;

window.__MUI_USE_NEXT_TYPOGRAPHY_VARIANTS__ = true;
console.log(localStorage);
class App extends React.Component {
  render() {
    return (
      <ThemeWrapper>
        <AppContext.Consumer>
          {changeMode => (
            <Switch>
              <Route path="/" exact component={Login} />
              <PrivateRoute isLoggedIn={isLoggedIn} exact path="/app" component={Application} />
              <Route
                path="/app"
                render={props => <Application {...props} changeMode={changeMode} />}
              />
              <Route component={Auth} />
              <Route component={NotFound} />
            </Switch>
          )}
        </AppContext.Consumer>
      </ThemeWrapper>
    );
  }
}

export default App;

authactions.js 将设置当前用户,但它只会发生一次,而不会在我重新加载后再次发生。

import axios from 'axios';
import jwt_decode from 'jwt-decode';
import setAuthToken from '../../utils/setAuthToken';

import { GET_ERRORS, SET_CURRENT_USER, USER_LOADING } from '../constants/authConstants';

// Login - get user token
export const loginUser = userData => dispatch => {
  axios
    .post('/api/total/users/login', userData)
    .then(res => {
      // Save to localStorage

      // Set token to localStorage
      const { token } = res.data;
      localStorage.setItem('jwtToken', JSON.stringify(token));
      // Set token to Auth header
      setAuthToken(token);
      // Decode token to get user data
      const decoded = jwt_decode(token);
      // Set current user
      dispatch(setCurrentUser(decoded));
      console.log('logged');
    })
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data,
      }),
    );
};

// Set logged in user
export const setCurrentUser = decoded => {
  return {
    type: SET_CURRENT_USER,
    payload: decoded,
  };
};

// User loading
export const setUserLoading = () => {
  return {
    type: USER_LOADING,
  };
};

// Log user out
export const logoutUser = history => dispatch => {
  // Remove token from local storage
  localStorage.removeItem('jwtToken);
  // Remove auth header for future requests
  setAuthToken(false);
  // Set current user to empty object {} which will set isAuthenticated to false
  dispatch(setCurrentUser({}));

  // history.push('/app');
};

编辑:当我查看 redux devtools 时,我发现 IF 块每次刷新时都会运行,但正确的状态似乎没有传递给其他组件。其他组件第一次获得正确的状态(isAuthenticated:true),但一旦我刷新,它们就会返回到 false。在 redux devtools 中,我每次刷新时都会看到这一点。

主减速器

/**
 * Combine all reducers in this file and export the combined reducers.
 */

import { reducer as form } from 'redux-form/immutable';
import { combineReducers } from 'redux-immutable';
import { connectRouter } from 'connected-react-router/immutable';
import history from 'utils/history';

import languageProviderReducer from 'containers/LanguageProvider/reducer';
import uiReducer from './modules/ui';
import initval from './modules/initForm';
import login from './modules/login';
import treeTable from '../containers/Tables/reducers/treeTbReducer';
import crudTable from '../containers/Tables/reducers/crudTbReducer';
import crudTableForm from '../containers/Tables/reducers/crudTbFrmReducer';
import ecommerce from '../containers/SampleApps/Ecommerce/reducers/ecommerceReducer';
import contact from '../containers/SampleApps/Contact/reducers/contactReducer';
import chat from '../containers/SampleApps/Chat/reducers/chatReducer';
import email from '../containers/SampleApps/Email/reducers/emailReducer';
import calendar from '../containers/SampleApps/Calendar/reducers/calendarReducer';
import socmed from '../containers/SampleApps/Timeline/reducers/timelineReducer';
import taskboard from '../containers/SampleApps/TaskBoard/reducers/taskboardReducer';

/**
 * Branching reducers to use one reducer for many components
 */

function branchReducer(reducerFunction, reducerName) {
  return (state, action) => {
    const { branch } = action;
    const isInitializationCall = state === undefined;
    if (branch !== reducerName && !isInitializationCall) {
      return state;
    }
    return reducerFunction(state, action);
  };
}

/**
 * Merges the main reducer with the router state and dynamically injected reducers
 */
export default function createReducer(injectedReducers = {}) {
  const rootReducer = combineReducers({
    form,
    ui: uiReducer,
    initval,
    login,
    socmed,
    calendar,
    ecommerce,
    contact,
    chat,
    email,
    taskboard,
    treeTableArrow: branchReducer(treeTable, 'treeTableArrow'),
    treeTablePM: branchReducer(treeTable, 'treeTablePM'),
    crudTableDemo: branchReducer(crudTable, 'crudTableDemo'),
    crudTableForm,
    crudTbFrmDemo: branchReducer(crudTableForm, 'crudTbFrmDemo'),
    language: languageProviderReducer,
    router: connectRouter(history),
    ...injectedReducers,
  });

  // Wrap the root reducer and return a new root reducer with router state
  const mergeWithRouterState = connectRouter(history);
  return mergeWithRouterState(rootReducer);
}

创建商店.js

/**
 * Create the store with dynamic reducers
 */

import { createStore, applyMiddleware, compose } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import { fromJS } from 'immutable';
import createSagaMiddleware from 'redux-saga';
import thunk from 'redux-thunk';

import createReducer from './reducers';

export default function configureStore(initialState = {}, history) {
  let composeEnhancers = compose;
  const reduxSagaMonitorOptions = {};

  // If Redux Dev Tools and Saga Dev Tools Extensions are installed, enable them
  /* istanbul ignore next */
  if (process.env.NODE_ENV !== 'production' && typeof window === 'object') {
    /* eslint-disable no-underscore-dangle */
    if (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) {
      composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ trace: true });
    }

    // NOTE: Uncomment the code below to restore support for Redux Saga
    // Dev Tools once it supports redux-saga version 1.x.x
    if (window.__SAGA_MONITOR_EXTENSION__)
      reduxSagaMonitorOptions = {
        sagaMonitor: window.__SAGA_MONITOR_EXTENSION__,
      };
    /* eslint-enable */
  }

  const sagaMiddleware = createSagaMiddleware(reduxSagaMonitorOptions);

  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middleware = [thunk];
  const middlewares = [...middleware, sagaMiddleware, routerMiddleware(history)];

  const enhancers = [applyMiddleware(...middlewares)];

  const store = createStore(createReducer(), fromJS(initialState), composeEnhancers(...enhancers));

  // Extensions
  store.runSaga = sagaMiddleware.run;
  store.injectedReducers = {}; // Reducer registry
  store.injectedSagas = {}; // Saga registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      store.replaceReducer(createReducer(store.injectedReducers));
    });
  }

  return store;
}

主应用程序文件

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import NotFound from 'containers/Pages/Standalone/NotFoundDedicated';
import jwtDecode from 'jwt-decode';
import configureStore from '../../redux/configureStore';
import { setCurrentUser, logoutUser } from '../../redux/actions/authActions';
import setAuthToken from '../../utils/setAuthToken';
import Auth from './Auth';
import Application from './Application';
import ThemeWrapper, { AppContext } from './ThemeWrapper';
import { PrivateRoute } from './PrivateRoute';

window.__MUI_USE_NEXT_TYPOGRAPHY_VARIANTS__ = true;
const initialState = {};

const store = configureStore(initialState);
const auth = localStorage.jwtToken ? true : false;
// Check for token to keep user logged in
if (localStorage.jwtToken) {
  // Set auth token header auth
  const token = JSON.parse(localStorage.jwtToken);
  setAuthToken(token);

  // Decode token and get user info and exp
  const decoded = jwtDecode(token);

  // Set user and isAuthenticated
  store.dispatch(setCurrentUser(decoded));
  // Check for expired token
  const currentTime = Date.now() / 1000; // to get in milliseconds
  if (decoded.exp < currentTime) {
    // Logout user
    logoutUser();

    // Redirect to login
    window.location.href = './';
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
      errors: {},
    };
  }

  render() {
    return (
      <ThemeWrapper>
        <AppContext.Consumer>
          {changeMode => (
            <Switch>
              {/* <Route path="/" exact component={Login} /> */}
              <PrivateRoute
                path="/app"
                auth={auth}
                component={props => <Application {...props} changeMode={changeMode} />}
              />
              <Route component={Auth} />
              <Route component={NotFound} />
            </Switch>
          )}
        </AppContext.Consumer>
      </ThemeWrapper>
    );
  }
}

export default App;

感染减少剂

import React from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
import { ReactReduxContext } from 'react-redux';

import getInjectors from './reducerInjectors';

/**
 * Dynamically injects a reducer
 *
 * @param {string} key A key of the reducer
 * @param {function} reducer A reducer that will be injected
 *
 */
export default ({ key, reducer }) => WrappedComponent => {
  class ReducerInjector extends React.Component {
    static WrappedComponent = WrappedComponent;

    static contextType = ReactReduxContext;

    static displayName = `withReducer(${WrappedComponent.displayName ||
      WrappedComponent.name ||
      'Component'})`;

    constructor(props, context) {
      super(props, context);

      getInjectors(context.store).injectReducer(key, reducer);
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }

  return hoistNonReactStatics(ReducerInjector, WrappedComponent);
};

const useInjectReducer = ({ key, reducer }) => {
  const context = React.useContext(ReactReduxContext);
  React.useEffect(() => {
    getInjectors(context.store).injectReducer(key, reducer);
  }, []);
};

export { useInjectReducer };

减少注射器

import invariant from 'invariant';
import { isEmpty, isFunction, isString } from 'lodash';

import checkStore from './checkStore';
import createReducer from '../redux/reducers';

export function injectReducerFactory(store, isValid) {
  return function injectReducer(key, reducer) {
    if (!isValid) checkStore(store);

    invariant(
      isString(key) && !isEmpty(key) && isFunction(reducer),
      '(app/utils...) injectReducer: Expected `reducer` to be a reducer function',
    );

    // Check `store.injectedReducers[key] === reducer` for hot reloading when a key is the same but a reducer is different
    if (
      Reflect.has(store.injectedReducers, key)
      && store.injectedReducers[key] === reducer
    ) return;

    store.injectedReducers[key] = reducer; // eslint-disable-line no-param-reassign
    store.replaceReducer(createReducer(store.injectedReducers));
  };
}

export default function getInjectors(store) {
  checkStore(store);

  return {
    injectReducer: injectReducerFactory(store, true),
  };
}

使用持久状态。这是index.js 文件示例

function saveToLocalStorage(state) {
  try {
    const serializedState = JSON.stringify(state)
    localStorage.setItem('state', serializedState)
  } catch (err) {
    console.log(err)
  }
}

function loadFromLocalStorage() {
  try {
    const serializedState = localStorage.getItem('state');
    if (serializedState === null) return undefined;
    return JSON.parse(serializedState)
  } catch (err) {
    console.log(err)
    return undefined;
  }
}

const persistedState = loadFromLocalStorage();

const sagaMiddleware = createSagaMiddleware();
const store = createStore(
  reducer,
  persistedState,
  applyMiddleware(logger, sagaMiddleware))
sagaMiddleware.run(watchLoadData);

store.subscribe(() => saveToLocalStorage(store.getState()))

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <App />
    </Provider>
  </BrowserRouter>,
  document.getElementById('root')
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 React/redux 状态会在刷新时重置? 的相关文章

  • 退出动画在下一个 js 帧器运动中不起作用?

    我在我的应用程序中使用 next js 在我的动画中使用成帧器运动 我可以设置介绍动画 但退出动画根本不起作用 我已将代码包装在动画效果下 但它没有执行任何操作 我在这里缺少什么 下面是我的示例代码
  • 无限水平滚动 Div

    我需要一个 div 当您将鼠标进一步向右或向左移动时 它会水平滚动 我发现 Smooth Div Scroll 插件 http www smoothdivscroll com 非常接近我的需要 然而 这存在一些问题 我需要能够使滚动元素从设
  • 如何将 CAD (DWG) 文件转换为 GeoJSON?

    我正在使用 OpenLayers 需要将 DWG 文件转换为 GeoJSON 格式 我怎样才能做到这一点 事实上 GDAL 拥有完成此任务所需的工具 ogr2ogr 是 GDAL 中包含的一个程序 可以转换多种格式 https gdal o
  • .addClass 仅添加到无序列表中单击的项目符号

    我有一个简短的无序列表 其中有两个项目符号 我添加了一些 Javascript 这样当我单击项目符号时 它会向其中添加一个类 问题是 它将该类添加到所有现有的 li 中 而不仅仅是我单击的那个 这是 JSFiddle http jsfidd
  • “成功”的 Netlify 表单提交未显示在仪表板中

    我有一个 create react app 应用程序部署到 Netlify 并且我正在使用反应网络化形式 https www npmjs com package react netlify form呈现我的表格 我的表单已在我的 Netli
  • 将 Blob 设置为 iframe 的“src”

    以下代码在 Chrome 中完美运行 但它不适用于 IE 有人可以告诉我这里出了什么问题吗 iframe src 也设置为 blob 如下所示
  • 获取与请求

    我正在使用 JSON 流并尝试使用 fetch 来使用它 该流每隔几秒发出一些数据 仅当流关闭服务器端时 使用 fetch 来使用流才可以访问数据 例如 var target the url var options method POST
  • d3 饼图中的文本被路径覆盖

    我正在尝试按照 d3 的饼图示例进行操作http bl ocks org mbostock 3887235 http bl ocks org mbostock 3887235 我的代码的最小示例 const container graph
  • 在 Promise 中中止 ajax 请求

    我正在构建一个表单验证并学习承诺 我决定使用承诺模式实现异步验证函数 var validateAjax function value return new Promise function resolve reject ajax data
  • 如何在phonegap中同时使用相机API选择多个图像?

    如何同时选择或拾取多个图像phonegap camera API使用时Camera DestinationType FILE URI 我一次只能选择一张图像 我可以使用以下命令在 SD 卡中选择多个文件 包括 txt pdf this ht
  • 重写node.js中其他模块中的函数

    我正在尝试在 Node js 应用程序中使用 nodeunit 存根函数 这是我正在尝试做的事情的简化版本 In lib file js var request require request var myFunc function inp
  • Angular 2.0 路由 - TS 2305 ...没有导出成员“ModulewithProviders”

    我正在关注一个角度2 0教程在 Angular JS 官方上site https angular io docs ts latest tutorial toh pt5 html并在路由练习结束时陷入困境 该代码上次有效 但前几天我点击 np
  • 在 Node.js 中封装 require 可以解决相对路径调用

    我正在尝试创建一个 require 包装器来加载依赖项 但我发现很难让它像原始的 require 函数一样工作 当路径是相对路径时 包装器无法解析为正确的路径 因为我的加载程序和调用程序文件不在同一文件夹中 这是一个简化的描述 index
  • 如何取消 ComponentWillUnmount 中的所有请求?

    根据docs https facebook github io react docs react component html componentwillunmount ComponentWillUnmount 能够取消请求 我有一个页面发
  • javascript:新日期,缺少年份

    我打电话给 new Date Jan 4 发现默认年份是2001年 a new Date Jan 4 Thu Jan 04 2001 00 00 00 GMT 0500 EST 有什么办法可以将默认年份设置为 2011 年吗 更新 我知道我
  • 如何在 Prisma 中指定可选查询过滤器?

    我正在使用 React Apollo 和 Prsima 构建一个应用程序 允许用户按型号 品牌 价格过滤汽车 我知道 例如 如何按品牌过滤汽车 const GET CARS gql query FilterCars brandId ID c
  • 有没有办法避开 Google 路线中的特定道路或坐标?

    API 有一个航路点参数 以便 API 计算经过指定航路点的路线 有什么方法可以给出要避开的航路点而不是要经过的航路点 它 目前 尚未实施 有一个开放的功能请求 问题 214 影响方向的能力 例如 避免 路障 https code goog
  • 将 ERB 与 Handlebars 模板结合使用

    我有一个使用 ajax 创建新标签的模式 它使用 Tags 参数执行 POST 方法 而无需重新充电视图 因此 我希望根据所选的 price type 参数来呈现一个或另一个价格 div 我使用 Handlebars 所以我想这不是 rub
  • Origin 无权使用地理定位服务 - 即使通过 HTTPS

    我有一个通过 HTTPS 使用 HTML5 地理定位的网页 它在桌面浏览器上运行良好 然而 在 iOS Safari 上 我收到错误 Origin 无权使用地理定位服务 我已确保页面上的所有内容都通过 HTTPS 加载 每个图像 每个脚本和
  • 在不调用“then”的情况下解决 Promise

    我有这段代码 它是我为一个名为 Poolio 的 NPM 模块编写的小型 API 的一部分 对于那些支持错误优先回调和承诺的人来说 我遇到的问题似乎是一个常见问题 我们如何在支持两者的同时保持一致的 API 和 API 的一致返回值 例如

随机推荐

  • Facebook 登录 onClick - Javascript

    我的网站上有这段代码 Facebook 登录对话框是在我的页面加载时显示的 而不是在用户单击锚标记时显示的
  • 如何在 Ruby 中逐行读取大型文本文件并将该流逐行追加到文件中?

    假设我想将几个大文件合并为一个 然后uniq 那个 光是这个就可能需要一秒钟的时间 我的理解是File readlines 将所有行加载到内存中 有没有办法逐行读取它 有点像node jspipe 系统有效吗 Ruby 的一大优点是您可以在
  • JavaScript 杂货清单

    我正在尝试创建一个杂货清单程序 现在我只是在做一些基本的功能 将商品添加到我的购物清单中 从购物清单中删除商品 查看购物清单以及标记我是否已拿起该商品 我困惑于如何让 标记 功能正常工作 这是我的代码 var groceryList fun
  • 如何在reactjs中设置背景图片?

    我有一个 ReactJS WebPack 应用程序并尝试为其设置背景图像body tag body background url images some background jpg background size contain back
  • 如何在没有构造函数的情况下将 React 组件的函数绑定到“this”?

    正如许多人所知 this someFunction this someFunction bind this 可以在 React 类组件中使用 然而 有时为非常简单的组件创建类是很麻烦的 那么 如何将函数绑定到this没有创建一个类 使用箭头
  • 如何在导航栏中正确位置的菜单内添加子菜单

    您好 我正在尝试在 HTML 中的正确位置的菜单内添加子菜单 但我在定位方面面临一个问题 我尝试使用 full 来解决这个问题ul and li标签 而不是 但我在尺寸方面仍然面临许多问题 所以我决定回到旧的方式 该示例位于链接中 我确信我
  • 如何将 HTML 内容放置在 Flash 影片上方?

    我正在开发的一个网站有 Flash 标题 使用swf对象 http code google com p swfobject 嵌入它们 现在我需要编写一些与 Flash 影片重叠的 HTML 代码 我尝试在 Flash 元素的容器和 绝对定位
  • 分配给ostream后如何关闭ofstream?

    I can do std ostream out condition std cout std ofstream filename 但如果出现以下情况我该如何关闭out std ofstream filename 忘记关闭一会儿 你的代码
  • TLS 连接握手失败

    我们很难与从我们的 Net 应用程序中禁用了 SSL3 协议的远程计算机 例如 PayPal vb 建立 https 连接 我们在 HttpWebRequest 实例的 GetResponse 方法上遇到以下异常 请求被中止 无法创建 SS
  • “您的 PATH 中没有 [PATH ],gem 可执行文件将无法运行。”使用“gem install --user-install bundler”时

    我试图在我的 Mac 上安装 jekyll 并收到如下警告 警告 您没有 Users Carrot gem ruby 2 3 0 bin 您的 PATH gem 可执行文件将不会运行 我检查了 gem list 它显示它已安装 我可以通过路
  • 多部分标识符无法绑定sql

    我在以下查询中收到多部分无法绑定错误 update nfltx set b boxno a boxno b message a message b nameboxno a nameboxno b namemsg a namemsg b ph
  • 使用 Promise.all 进行错误处理

    我遇到了有关 Promise all 错误处理的问题 我希望以下代码在其中之一时调用链的 catch 部分getNetworkstuff 承诺失败 但它只是调用下一个 then 部分 并且浏览器控制台显示未捕获的错误 Promise all
  • NLTK 的 Vader 评分文本示例

    我希望有人纠正我对 VADER 如何对文本进行评分的理解 我读过这个过程的解释here http datameetsmedia com vader sentiment analysis explained 但是 在重新创建它描述的过程时 我
  • jQuery:用 A 锚标记包装图像标记的最简单方法

    这是我的问题的简化版本 我有两个按钮和一张图像 图像代码是这样的 img class onoff src image jpg 当我按下按钮一时 我希望将图像包裹在 A 标签中 例如 a href link html img class on
  • 在什么情况下您会使用 new 关键字初始化值类型?

    我的问题是关于使用new对于值类型 int bool int i new int 在这种情况下i被初始化为零值 我读到这不是一个好东西new与值类型 但是 不动态分配内存 仅在堆栈上 那么问题是为什么 C 编译器制造商允许我们这样做 在什么
  • 如何隐藏 jQuery Validator 创建的标签?

    我目前正在对我的验证表单 红色背景和边框 应用一个简单的简单方法 尽管 jQuery 验证器附加了一些带有 Field is required 的标签 我只是不想出现任何文字 谢谢你 你可以覆盖errorPlacement option h
  • Notepad++ 不突出显示 HTML 文件中的 css [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 在 Notepad 中 HTML 文件中的 CSS 没有语法突出显示 可以启用吗 这个问题已在超级用户中得到回答不同语言语法突出显示 ht
  • React.useMemo 正在重新渲染数组中的所有项目

    我有一个 React 组件 它在 useState 中存储一组水果 我有一个过滤水果的记忆函数 visibleFruits 我将visibleFruits映射到dom 问题是 当我检查水果时 所有可见的水果都会重新渲染 我预计只有选定的一项
  • 如何在 Chrome 的 PDF 查看器中显示 javascript File 对象及其名称?

    我有一个 PDF 文件 格式为Blob https developer mozilla org en US docs Web API Blob Blob对象 生成为jsPDF https github com MrRio jsPDF 我想显
  • 为什么 React/redux 状态会在刷新时重置?

    当我登录时 一切正常 但当我点击刷新或导航到其他地方时 状态就会重置 知道为什么吗 我希望能够从状态引用用户并获取名称等信息并在组件内使用它 但它只有在我登录后才起作用 然后它就会重置 另外 为什么我必须在mapstatetoprops中使