有没有办法在另一个文件内的组件树之外更改 redux 中的状态?

Is there a way to change the state in redux outside the component tree inside another file?

我正在尝试在 api 脚本中更改组件外部的 redux 状态 我试过这个:

api 脚本:

import store from "./index.jsx";
import foo from "./actions.js";

const state = store.getState();
store.dispatch(foo("Hello world!"));
/*^^^ERROR^^^ Error message: state.dispatch is not a function*/

index.js:

//Importing packages
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App.jsx";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducers from "./redux/reducers/index.js";

//Redux configuration
export const store = createStore(reducers);

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

reportWebVitals();

谁能帮忙谢谢!

亲切的问候阿尔文。

更新:我在此代码中发现了另一个问题: 当我 运行 代码没有错误但是当我 运行 通过按下按钮这个函数时它给我这个错误:

action of type "AUTH_SIGN_IN", the slice reducer for key "login" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.

你不能 dispatch 使用 state 这样 state.dispatch(foo("Hello world!")); 你可以 dispatch 使用 store。 你可以这样做 store.dispatch(foo("Hello world!"));.

示例:

import React from "react";
import ReactDOM from "react-dom";
import * as ReactRedux from "react-redux";
import * as Redux from "redux";

function onIncriment() {
  return {
    type: "INCRIMENT"
  };
}

const initialState = {
  counter: 0
};

function counterReducer(state = initialState, action) {
  switch (action.type) {
    case "INCRIMENT": {
      return {
        ...state,
        counter: state.counter + 1
      };
    }
    default:
      return state;
  }
}

const staticReducer = {
  counter: counterReducer
};

let store = Redux.createStore(Redux.combineReducers({ ...staticReducer }));

function App() {
  return <div>Counter value : {store.getState().counter.counter} </div>;
}

ReactDOM.render(
  <ReactRedux.Provider store={store}>
    <App />
  </ReactRedux.Provider>,
  document.getElementById("root")
);

store.dispatch(onIncriment())

您必须在单独的文件上创建商店(我通常有 src/store.ts)。您将能够在 index.js 上导入您的商店(对于 React 提供商),您也可以将其导入到 React 之外,只需 store.dispatch(...).