React-Redux:reducer只返回初始状态

时间:2020-01-07 06:32:06

标签: javascript reactjs redux

当我在react应用中使用redux时,reducer会为我返回初始状态。此处始终返回false。感谢您的回答。

[更新]: 我哭了

let newState = state 

对此:

 let newState = {...state}

而且reducer返回false

这是我的减速器

 const initialState = {
      modalVisible: false
    };
    function modalReducer(state = initialState, action) {
      let newState = {...state};
      switch (action.type) {
        case "SHOW":
          newState.modalVisible = true;
          console.log("Show!");
          break;
        case "HIDE":
          newState.modalVisible = false;
          console.log("Hide!");
          break;
      }
      return newState;
    }

export default modalReducer;

这是我的组件(Svg Viewer组件)

import React from "react";

import { connect } from "react-redux";

const SvgViewer = ({
  nodesData,
  svgFilePath,
  modalVisible,
  onModalShow,
  onModalHide
}) => {

  const clickHandler = () => {
    onModalShow();
    console.log(modalVisible); //return false
    onModalHide();
    console.log(modalVisible);
  };

  return (
    <div className="unit-schema-container1" key={svgFilePath}>
      <object id="svgobject" type="image/svg+xml" data={svgFilePath}></object>
      <button onClick={clickHandler}></button>
    </div>
  );
};

const mapStateToProps = state => {
  return { modalVisible: state.modalVisible };
};

const mapDispatchToProps = dispatch => {
  return {
    onModalShow: () => {
      dispatch({ type: "SHOW" });
    },
    onModalHide: () => {
      dispatch({ type: "HIDE" });
    }
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(SvgViewer);

3 个答案:

答案 0 :(得分:1)

您应该尝试使用它。它更易于阅读和使用最佳做法

const initialState = {
  modalVisible: false
};

function modalReducer(state = initialState, action) {
  switch (action.type) {
    case "SHOW":
      return {...state, modalVisible: true }
    case "HIDE":
      return {...state, modalVisible: false }
    default:
      return state
  }
}

答案 1 :(得分:0)

您应该返回一个新的状态对象

let newState = {...state}

答案 2 :(得分:0)

我认为问题出在mapStateToprops函数中,请发布您的主要reducer, 尝试编辑mapStateToProps

const mapStateToProps = state => {
  return { modalVisible: state.modalVisible.modalVisible  };
};