我试图在React JS中创建可重用的组件。
汽车组件如下:
class cars extends React.Component {
constructor(props){
super(props);
this.state = {
notification: {
showNotification: false,
message: null,
icon: null
},
carID: null
};
}
componentWillReceiveProps(nextProps){
let totalCarsPrevious = this.props.carsInCart.length;
let totalCarsNext = nextProps.carsInCart.length;
let initNotification = {showNotification: false, message: null, icon: null};
let notificationRemoved = {showNotification: true, message: notification_messages.removedFromCart, icon: "times"};
let notificationAdded = {showNotification: true, message: notification_messages.addedToCart, icon: "check"};
if(totalCarsNext !== totalCarsPrevious){
this.setState({notification: initNotification}, () => {
if(totalCarsNext > totalCarsPrevious){
this.setState({notification: notificationAdded});
}else{
this.setState({notification: notificationRemoved});
}
});
}
}
render() {
let showNotification = this.state.notification.showNotification ? <Notification message={this.state.notification.message} icon={this.state.notification.icon} /> : "";
return (
<div>
{showNotification}
//Rest of the code ....
</div>
)
}
}
在componentWillReceiveProps
内的汽车组件中,我检查redux存储状态是否已更改。如果它被更改,那么我会显示通知。
通知组件如下:
import React, {PropTypes} from 'react';
import FontAwesome from 'react-fontawesome';
export const notification_messages = {
addedToCart: "Added",
removedFromCart: "Removed",
addToFavorites: "Added to favorites",
removedFromFavorites: "Removed to favorites"
};
export default class Notification extends React.Component {
constructor(props) {
super(props);
this.state = {
opacity: 0,
};
}
componentWillMount() { this.hideNotification = null; }
componentDidMount() { this.setTimeout(); }
setTimeout() {
this.setState({opacity: 1}, () => {
this.hideNotification = setTimeout(() => this.setState({opacity: 0}), 2500);
});
}
componentWillUnmount() { if(this.hideNotification !== null) clearTimeout(this.hideNotification); }
render() {
console.log("Pozvana je")
let {message, icon} = this.props;
let styles = {opacity: this.state.opacity, transition: "opacity 2s ease"};
return (
<div className="notification" style={styles}>
<div> <FontAwesome name={icon}/> {message} </div>
</div>
);
}
}
Notification.propTypes = {
message: PropTypes.string.isRequired,
icon: PropTypes.string
};
这很完美。但是现在我想重用这个通知组件。我有相同的逻辑来添加和删除收藏夹。
我可以通过向收藏夹组件添加相同的状态和相同的componentWillReceiveProps
来实现。然后我只需要检查this.props.favorites.length
和nextProp.favorites.length
而不是this.props.carsInCart.length
和nextProp.carsInCart.length
。
但有什么方法可以避免这种情况吗?
我想将componentWillReceiveProps
中的状态和逻辑添加到通知组件中,然后只使用我需要比较的值来调用它。
但每当父组件(汽车或收藏夹)收到新道具时,我都需要这样做。
知道怎么做吗?