【问题标题】:The problem with redux not working on button clickredux 在按钮单击时不起作用的问题
【发布时间】:2020-02-02 22:32:57
【问题描述】:

我是 Redux 的新手,正在学习如何将它与 React 一起使用。基本上,在使用 React 应用程序设置 Redux 方面,我做的一切都是正确的,但是当我单击按钮增量时,我希望显示的计数器会加一。但是当我这样做时,什么也没有发生,当然,我已经检查了调度和正在发送的操作,但基本上一切都很好。因此,我真的需要你们的帮助,这里是我正在使用的代码:

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
import { createStore } from "redux";
import reducer from "./store/reducer";
import { Provider } from "react-redux";

const store = createStore(reducer);
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);
registerServiceWorker();

reducer.js

const initialState = {
  counter: 0
};

const reducer = (state = initialState, action) => {
  if (action.type === "INCREMENT") {
    return { counter: state.counter + 1 };
  }

  return state;
};

export default reducer;

counter.js

import React, { Component } from "react";
import { connect } from "react-redux";

import CounterControl from "../../components/CounterControl/CounterControl";
import CounterOutput from "../../components/CounterOutput/CounterOutput";

class Counter extends Component {
  render() {
    return (
      <div>
        <CounterOutput value={this.props.ctr} />
        <CounterControl
          label="Increment"
          clicked={() => this.props.onIncrement}
        />
      </div>
    );
  }
}

const mapStateToProps = state => {
  return { ctr: state.counter };
};

const mapDispatchToProps = dispatch => {
  return {
    onIncrement: () => dispatch({ type: "INCREMENT" })
  };
};

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

【问题讨论】:

  • 我没有看到 countercontrol 但您没有执行 onIncrement 函数:clicked={() =&gt; this.props.onIncrement()} 缺少 ()。也无需重新创建函数:clicked={this.props.onIncrement} 应该可以工作。 Counter 不需要是类,可以定义为函数:const Couner = ({onIncrement,ctr})=&gt;(&lt;div&gt;,,,clicked={onIncrement})
  • 另外看看reselect你的CounterContainer(错误地称为Counter并且错误地返回jsx)假设知道可以找到它的道具的路径state.counter。这里也没有发生记忆,所以即使state.counter 没有改变你的计数器也会重新渲染。
  • @HMR,谢谢你的好心 cmets,你的意思是,既然我们只有存储,我们可以只使用没有类容器的函数容器对吗?另外,您使用 immutable.js 是最佳做法吗?
  • 我认为不需要 Immutablejs,因为我们已经传播了:newState = {...oldState, newValue}。 Counter 不需要是一个类,因为它唯一的方法是渲染,没有代码需要它是一个类。
  • @HMR,好的,我将 clicked={() => this.props.onIncrement} 更改为 clicked={() => this.props.onIncrement()} 并且它有效。但是等一下,即使我没有点击按钮,clicked={() => this.props.onIncrement()} 也不应该立即运行代码吗?

标签: reactjs redux


【解决方案1】:

你是否在 store 中注册了你的 reducer?

如果没有,请这样做。

我相信这个东西不应该返回字符串:

const mapStateToProps = state => {
  return { ctr: state.counter };
};

【讨论】:

  • 嗨,Vishal,谢谢您的友好回答,您认为问题出在此处吗 const mapStateToProps = state => { return { ctr: state.counter }; }; ??
  • @Dickens 我认为你应该先在商店注册你的减速器。然后你就可以在这里访问了,
猜你喜欢
  • 2014-03-24
  • 2017-03-09
  • 1970-01-01
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
相关资源
最近更新 更多