我使用新的getDerivedStateFromProps
,因为componentWillReceiveProps
已被弃用。但是它似乎没有按预期工作,因为在更新Redux状态后没有任何反应。
预期
props.modal
已更新,组件重新呈现结果
"react": "^16.3.2",
"react-dom": "^16.3.2",
请注意,在此屏幕截图中,我可以更新Redux状态,modal
已更新,但我的组件未更新并重新呈现。
我希望第二次调用此代码:
static getDerivedStateFromProps(nextProps, nextState) {
const { modal } = nextProps;
console.log('getDerivedStateFromProps', nextProps);
console.log(' nextState', nextState);
return { modal };
}
或者至少我的render方法中的console.log被称为两次,这种情况从未发生过。有什么想法吗?
import React, { Component } from "react";
import { connect } from "react-redux";
// MUI
import { withStyles } from "@material-ui/core/styles";
// Components
import TopNav from "components/Common/topNav";
// import ProductModal from 'components/Common/productModal';
// Utils
import { findNotification, showNotification } from "utils/notifications";
const styles = {
root: {
flexGrow: 1,
display: "flex",
flexDirection: "column",
height: "100%"
}
};
class Main extends Component {
static getDerivedStateFromProps(nextProps, nextState) {
const { modal } = nextProps;
console.log("getDerivedStateFromProps", nextProps);
console.log(" nextState", nextState);
return { modal };
}
constructor(props) {
super(props);
this.state = {
modal: {}
};
}
componentDidUpdate(props) {
console.log("componentDidUpdate", props);
}
render() {
const {
classes,
children,
notifications,
currentNotification
} = this.props;
console.log("this.props", this.props);
console.log("this.state", this.state);
const notificationObj = findNotification(
currentNotification,
notifications
);
return (
<div className={classes.root}>
{/* <ProductModal /> */}
<TopNav />
{showNotification(notificationObj)}
{children}
</div>
);
}
}
const mapStateToProps = ({ modal }) => ({
modal
});
export const MainJest = Main;
export default connect(
mapStateToProps,
null
)(withStyles(styles)(Main));
import {
MODAL_CLOSE_MODAL,
MODAL_SET_MODAL
} from 'actions/types';
export const initialState = {
modal: {
name: '',
props: {}
}
};
const modalsReducer = (state = initialState, { type, payload }) => {
switch (type) {
case MODAL_SET_MODAL:
return {
...state,
modal: {
name: payload.modalName,
props: payload.modalProps
}
};
case MODAL_CLOSE_MODAL:
return {
...state,
modal: {
name: '',
props: {}
}
};
default:
return state;
}
};
export default modalsReducer;
答案 0 :(得分:0)
原来我的问题出在mapStateToProps
需要从modalsReducer
const mapStateToProps = (state) => {
console.log('mapStateToProps state:', state);
return state.modalsReducer;
};
还需要在modalsReducer
import {
MODAL_CLOSE_MODAL,
MODAL_SET_MODAL
} from 'actions/types';
export const initialState = {
modalName: '',
modalProps: {}
};
const modalsReducer = (state = initialState, { type, payload }) => {
switch (type) {
case MODAL_SET_MODAL:
return {
...state,
modalName: payload.modalName,
modalProps: payload.modalProps
};
case MODAL_CLOSE_MODAL:
return {
...state,
modalName: '',
modalProps: {}
};
default:
return state;
}
};
export default modalsReducer;
所以Redux没有正确连接......