when i using redux in my react app,reducer just return initial state for me.which is always returned the false here.thanks for your answer.
[UPDATE]: i chaned
let newState = state
to this:
let newState = {...state}
but also reducer returned false
this my reducer:
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;
and this is my component (Svg Viewer component)
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);
You should try using this. Its easier to read and uses the best practices
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}
I think the problem is in mapStateToprops function, please post your main reducer, try to edit you mapStateToProps
const mapStateToProps = state => {
return { modalVisible: state.modalVisible.modalVisible };
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.