【问题标题】:Redux state not updating when action dispatched from a non-react file从非反应文件分派操作时 Redux 状态未更新
【发布时间】:2018-09-03 01:36:56
【问题描述】:

我正在实现 react-bootstrap-table-next 并且需要获取单击的标题列值以发送到数据库以在服务器端对其进行排序。我想将点击的列名传递给 redux 存储。我可以在登录操作中获取单击的值,但我的状态不会在 redux 中更新。

import { createStore } from 'redux';
import reducer from '../../reducers/index';

const initialState = window.__INITIAL_STATE__; // eslint-disable-line
const store = createStore(reducer, initialState);    
const columnClick = dataField => (event) => {
  const action = sortColName(dataField);
  store.dispatch(action);
};

export const columns = [
  {
    dataField: 'name',
    text: 'Name',
    headerEvents: {
      onClick: columnClick('name'),
    },
  }, {
    dataField: 'address',
    text: 'Address',
  }, {
    dataField: 'type',
    text: 'Type',
  }, {
    dataField: 'account_name',
    text: 'Account Name',
  }, {
    dataField: 'environment',
    text: 'Environment',
  }];

这是我的行动。

export const sortColName = (event) => {
  console.log(event);
  return {
    type: ACTION_TYPES.SORT_COL_NAME,
    data: event,
  };
};

这是我的减速机。

import * as ACTION_TYPES from '../consts/action_types';

const initialState = {
  sortColName: '',
};

export const getSortColName = (state = initialState, action) => {
  switch (action.type) {
    case ACTION_TYPES.SORT_COL_NAME:
      return {
        ...state,
        sortColName: action.data,
      };
    default:
      return state;
  }
};

这是我的 store.js

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import { routerMiddleware } from 'react-router-redux';
import axios from 'axios';
import rootReducer from '../reducers/index';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export const configureStore = (history, initState) => {
  const middlewares = [thunk.withExtraArgument(axios), logger, routerMiddleware(history)];
  const store = createStore(
    rootReducer,
    initState,
    composeEnhancers(applyMiddleware(...middlewares)),
  );
  return store;
};

当我运行这个说窗口未定义时出现错误。

我使用 combineReducers 将 reducer 连接到主 index.js 文件,并使用 mapStateToProps 获取组件中的值,但状态不会更新。

【问题讨论】:

  • 您需要发送您的操作。

标签: reactjs redux react-redux


【解决方案1】:

创建后,您需要将操作分派到 redux 存储。像这样:

import {createStore} from 'redux'

store = createStore(reducer, initialState)

const columnClick = dataField => () => {
  const action = sortColName(dataField);
  store.dispatch(action) // <-- MISSING LINE
};

这将更新商店的状态并通知订阅的组件。

【讨论】:

  • 我这里有 3 个文件。包含列的主文件没有与存储相关的任何内容。所以上面的代码应该放在我的reducers或者我创建列的js文件中?
  • 需要在事件上调度动作。你可以参考完整的例子 react-redux here
  • @ashton 我做到了。我仍然没有通过 redux 开发工具看到 store 中的值,但是在 reducer 中登录了控制台
猜你喜欢
  • 2020-11-09
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 2019-12-04
  • 2020-04-22
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
相关资源
最近更新 更多