Estoy tratando de cambiar el estado redux fuera de un componente en un script api. He intentado esto:
secuencia de comandos 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*/índice.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();¿Puede alguien por favor ayudar gracias!
Saludos cordiales Alvin.
ACTUALIZACIÓN: He encontrado otro problema en este código: cuando ejecuto el código no hay errores, pero cuando ejecuto esta función presionando un botón, me da este error:
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.No puede dispatch usando el state como este state.dispatch(foo("Hello world!")); Puedes dispatch usando la store . Puedes hacerlo así store.dispatch(foo("Hello world!")); .
Ejemplo :
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())Debe crear la tienda en un archivo separado (normalmente tengo src/store.ts). Podrá importar su tienda en index.js (para el proveedor de React) y también podrá importarla fuera de React y simplemente store.dispatch(...) .