为什么reducer不响应action?

IT技术 reactjs redux react-redux
2021-05-19 07:00:13

试图使减速器工作,但每次“默认”情况都会触发。这是代码:

交流:

import {INPUT_IDEA_HANDLE} from "./types"

export function inputIdeaHandle(idea) {
  console.log('it is working, I have access to the idea');
  return {
    type: INPUT_IDEA_HANDLE,
    payload: idea
  }
}

减速机:

import {INPUT_IDEA_HANDLE} from "../actions/types"

export default function (state = null, action) {
  switch (action.type) {
    case INPUT_IDEA_HANDLE :
      console.log('never fires');
      return action.payload;
    default:
      console.log('fires everytime');
      return state
  }
}

import { combineReducers } from "redux";
import inputIdeaReducer from "./inputIdeaReducer.js"

export default combineReducers({
  inputIdea: inputIdeaReducer
});

更新 我改变了我的触发代码,但不断得到

无法读取的未定义的属性“props”返回this.props.inputHandle(值);

事件触发器:

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { inputIdeaHandle } from "../actions";

class Dashboard extends Component {
  changeHandle(e) {
    e.preventDefault();
    let value = e.target.value;
    return this.props.inputHandle(value);
  }

  render() {
    return (
      <div className="dashboard container">
        <div className="row">
          <div className="col-12">
            <h4>Type your idea here</h4>
            <input
              type="text"
              onChange={this.changeHandle}
              value={this.props.inputIdea}
            />
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    inputIdea: state.inputIdea
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      inputHandle: inputIdeaHandle
    },
    dispatch
  );
}

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

Triple 检查了所有内容,但仍然在控制台中“每次都触发”。依靠你,伙计们

问候

2个回答

问题在于处理this上下文。

您可以this按如下方式处理上下文

  1. constructor

    constructor() { super(props); this.changeHandle = this.changeHandle.bind(this)}; }

  2. Arrow function in renderonChange={e => this.changeHandle(e)}

  3. React.createClassReact binds all functions to this.
  4. Bind in renderonChange={this.changeHandle.bind(this)}
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

你必须从你的动作文件中导入你的动作 import { postSelected } from '../containers/actions';

class Home extends Component {
  changeHandle(e) {
    e.preventDefault();
    let value = e.target.value;
     return this.props.post(value);
  }

    <input type="text" onChange={this.changeHandle} />

} //end of class

function mapStateToProps(state) {
  return{
    view: state.view
  }
}

function mapDispatchToProps(dispatch) {
   return bindActionCreators({
     post: postSelected,
   },dispatch)
 }

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

这应该可以编辑它以满足您的需求