繁体   English   中英

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

[英]React-Redux:reducer only return initial state

当我在我的反应应用程序中使用 redux 时,reducer 只是为我返回初始状态。这里总是返回 false。谢谢你的回答。

[更新]:我改变了

let newState = state 

对此:

 let newState = {...state}

但也减速机返回假

这是我的减速机:

 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);

你应该尝试使用这个。 它更易于阅读并使用最佳实践

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
  }
}

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

let newState = {...state}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM