动作未触发-react-redux计数器示例

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

我正在尝试使用redux设置我的react项目,并且我正在使用一个基本示例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

javascript reactjs redux react-redux
1个回答
1
投票

更新需要正确定义mapDispatchToProps函数并将其传递给connect()。在您的代码中increment()似乎没有调度动作。

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

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

更新该错误归因于组件外部的useDispatch()使用。它必须在功能组件中声明和使用。

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