【问题标题】:Why is the correct action not triggering while dispatching?为什么调度时没有触发正确的操作?
【发布时间】:2021-11-08 01:46:47
【问题描述】:

动作

export const VERIFY = () => dispatch => {
    dispatch({type: "VERIFY"})
};

减速器

const signedReducer = (state=user, action) => {
    console.log(action);

    switch(action.type){
     
        case "VERIFY": {
            return {...state, email: "example@gmail.com"};
        }
        default: {
            return state;
        }
    }

}

_app.js代码

import { wrapper } from '../redux/store';

function MyApp({ Component, pageProps }) {

  return <>
    <Component {...pageProps}/>
  </>
}

MyApp.getInitialProps = async(appContext) => {
  let { pageProps } = appContext
    pageProps = {};
    if(appContext.Component.getInitialProps){
     
      pageProps = await appContext.Component.getInitialProps(appContext.ctx);
    }

    return {
      pageProps,
 
    };
};

export default wrapper.withRedux(MyApp);

& 最后pages/home.js

import { useEffect } from "react";
import PrivateLayout from "../components/PrivateLayout/PrivateLayout";
import { connect } from "react-redux";
import { VERIFY } from "../redux/actions/signActions";

function Home() {
  // console.log(user);

  // useEffect(() => {

  // }, [user]);

  
  return (
      <div >
        { true ? 
            <h1>Logged In</h1> 
                  : 
            <h1>Please login again</h1>
        }
      </div>
  )
}

const mapStateToProps = state => ({
  user: state
})

const mapDispatchToProps = {
  VERIFY: VERIFY
}

export default connect(mapStateToProps, mapDispatchToProps)(Home);

请检查,我已经在 reducer 中添加了一个 console.log 语句。 每当我运行代码时,console.log 语句只显示这些操作类型

  • @@redux/INIT6.z.d.a.h.7
  • @@redux/PROBE_UNKNOWN_ACTIONq.x.h.3.5.d

但从不采取行动VERIFY。 浏览了互联网,但没有找到任何解决方案。为什么?

【问题讨论】:

  • 您想在什么时候调用该操作?因为我在您的 Home 组件中没有看到任何操作调用。
  • 当页面打开或从其他页面重定向时,我希望触发该操作。我在想这个动作会被触发。请举例说明如何触发。
  • @Ammar 你是对的,谢谢你的回复。

标签: reactjs redux next.js redux-thunk


【解决方案1】:

这应该可以解决您的问题:

您还需要在组件中调用 VERIFY。

行动:

export const VERIFY = () => ({type: "VERIFY"});

参考:https://react-redux.js.org/using-react-redux/connect-mapdispatch

【讨论】:

    猜你喜欢
    • 2020-05-22
    • 2021-07-03
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 2021-03-15
    • 2022-06-16
    • 2017-03-15
    相关资源
    最近更新 更多