簡體   English   中英

未觸發操作 - react-redux 反例

[英]Action not being fired - react-redux counter example

我正在嘗試使用 redux 設置我的反應項目,並且我正在遵循一個帶有counter的基本示例,我可以遞增和遞減它。 計數器最初在頁面上正確顯示為0 - 但是當我點擊按鈕時,似乎沒有調度increment操作,因此,計數器不會更新。

我的LoginPage.js

/* eslint-disable no-unused-expressions */
import { connect } from "react-redux";
import React, { Component } from "react";
import { selectCounter } from "./../../selectors/counter";
import { actions as counterActions } from "./../../actions/counter";

class LoginPage extends Component {
  componentDidMount() {}

  render() {
    const { counter, increment } = this.props;
    return (
      <div>
        <p>{`Hi ${counter}`}</p>
        <button onClick={() => increment()}>+</button>
      </div>
    );
  }
}

LoginPage = connect(
  (state, props) => ({
    counter: selectCounter(state, props)
  }),
  { ...counterActions }
)(LoginPage);

export default LoginPage;

我的actions/counter.js

import { INCREMENT } from "./../types/counter";

const increment = () => {
  return { type: INCREMENT };
};

export const actions = {
  increment
};

我的/reducers/counter.js

const { INCREMENT, DECREMENT } = "./../types/counter";

const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case INCREMENT:
      return state + 1;
    case DECREMENT:
      return state - 1;
    default:
      return state;
  }
};

module.exports = { counterReducer };

我的/reducers/index.js

import { combineReducers } from "redux";
import { counterReducer } from "./counter";

const rootReducer = combineReducers({
  counter: counterReducer
});

export default rootReducer;

我省略了App.jsindex.js文件,因為它們非常簡單,似乎與問題無關。

更新:

我的actions/counter.js

import { INCREMENT } from "./../types/counter";
import { useDispatch } from "react-redux";

const increment = () => {
  return { type: INCREMENT };
};

const mapDispatchToProps = dispatch => {
  return {
    increment: () => dispatch(increment())
  };
};

export const actions = {
  ...mapDispatchToProps(useDispatch)
};

現在我看到了這個錯誤:

react-dom.development.js:14724 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app

更新
需要正確定義mapDispatchToProps function 並將其傳遞給connect() 在您的代碼中, increment()似乎沒有調度動作。

const mapDispatchToProps = (dispatch) =>{
    increment: ()=>dispatch(actions.increment())
}

LoginPage = connect(
  (state, props) => ({
    counter: selectCounter(state, props)
  }),
  mapDispatchToProps
)(LoginPage);

更新錯誤是由於組件外部使用了useDispatch() 它必須在功能組件中聲明和使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM