我正在尝试设计一个通知组件,其中通知将在某些场合出现(如连接问题,成功修改等).
我需要在几秒钟后消失通知,因此我触发状态更改以从通知setTimeout内部删除Redux状态的通知componentDidMount.
我可以看到状态确实发生了变化,但React-Redux没有重新渲染父组件,因此通知仍然出现在DOM上.
这是我的Redux减速机:
const initialState = {
notifications: []
}
export default function (state = initialState, action) {
switch(action.type) {
case CLEAR_SINGLE_NOTIFICATION:
return Object.assign ({}, state, {
notifications: deleteSingleNotification(state.notifications, action.payload)
})
case CLEAR_ALL_NOTIFICATIONS:
return Object.assign ({}, state, {
notifications: []
})
default:
return state
}
}
function deleteSingleNotification (notifications, notificationId) {
notifications.some (function (notification, index) {
return (notifications [index] ['id'] === notificationId) ?
!!(notifications.splice(index, 1)) :
false;
})
return notifications;
}
Run Code Online (Sandbox Code Playgroud)
和我的React组件(Main和Notification …
我想知道渲染方法上的解构道具是否会影响性能,因为每次创建它们时都会创建一个新常量,并且在浅比较时(如果您使用 PureComponent),浅比较将返回false,从而重新渲染所有子项。
下面的例子:
export default class Input extends React.PureComponent {
render () {
// creating new constants, that in case they are no primitives
// will return false when shallow comparing them and trigger
// child component re-render
const { type, value, required } = this.props
return (
<div className={cx('Input')}>
<APureComponent type={type} value={value} required={required} />
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)