Take 不侦听要分派的操作

问题描述 投票:0回答:1

我尝试在我的传奇中使用

yield take(action.type)

function* foo() {
  console.log('pausing')
  yield take(action.type)
  console.log('passing')
}

我确保在 useEffect 中发送了正确的操作


useEffect(() => {
   dispatch(action())
}, [action])

我还确保在正确设置传奇之后调度该操作。

操作在 Redux Toolkit 的切片中定义

import { createSlice } from '@reduxjs/toolkit';

const appSlice = createSlice({
  name: 'app',
  initialState: {},
  reducers: {
    appMounted: (state) => {
      // ... some state updates if needed
    },
    buttonClicked: (state) => {
      // ... some state updates if needed
    }
  }
});

export const { appMounted, buttonClicked } = appSlice.actions;
export default appSlice.reducer;`

我在生效中使用的操作类型与我正在调度的操作类型完全相同。

问题是,

'pausing'
已打印,但在我发送
action
后,
passing
未打印。

reactjs redux-toolkit redux-saga
1个回答
0
投票

确保在创建 redux 存储时将

redux-saga
中间件添加到 middleware

一个工作示例:

store.ts

import { configureStore } from "@reduxjs/toolkit";
import createSagaMiddleware from "redux-saga";
import appReducer from "./app.slice";
import saga from "./saga";

let sagaMiddleware = createSagaMiddleware();

const store = configureStore({
    reducer: {
        app: appReducer,
    },
    middleware: (getDefaultMiddleware) => getDefaultMiddleware({ thunk: false }).concat(sagaMiddleware),
});

sagaMiddleware.run(saga);

export default store;

saga.ts

import { take } from "redux-saga/effects";
import { appMounted } from "./app.slice";

export default function* foo() {
    console.log("pausing");
    yield take(appMounted().type);
    console.log("passing");
}

app.slice.ts

import { createSlice } from "@reduxjs/toolkit";

const appSlice = createSlice({
    name: "app",
    initialState: {},
    reducers: {
        appMounted: (state) => {
            // ... some state updates if needed
        },
        buttonClicked: (state) => {
            // ... some state updates if needed
        },
    },
});

export const { appMounted, buttonClicked } = appSlice.actions;
export default appSlice.reducer;

App.tsx

import React, { useEffect } from "react";
import "./styles.css";
import { useDispatch } from "react-redux";

import { appMounted } from "./app.slice";

export default function App() {
    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(appMounted());
    }, [dispatch]);

    return (
        <div className="App">
            <h1>Hello CodeSandbox</h1>
            <h2>Start editing to see some magic happen!</h2>
        </div>
    );
}

index.tsx

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";

const rootElement = document.getElementById("root")!;
const root = ReactDOM.createRoot(rootElement);

root.render(
    <Provider store={store}>
        <App />
    </Provider>,
);

控制台日志:

pausing 
passing 

代码沙盒

© www.soinside.com 2019 - 2024. All rights reserved.