Как отправить действие Redux без «onClick»?

#redux #react-redux

Вопрос:

Для приведенной ниже строки кода, как я могу отправить notificationsStateUpdate без onClick ? Я хочу, чтобы это действие было отправлено, если notificationClicked оно верно, поэтому в настоящее время у меня настроено троичное выражение.

Однако, похоже, я не могу заставить синтаксис работать. Возможна ли отправка в этом сценарии?

 {notificationClicked ?  lt;NotificationList   notifications={newNotifications} /gt;   dispatch(notificationsStateUpdate({newNotifications}))  : null}  

Полный код для контекста

 import React, { useState, useEffect, useRef } from 'react'; import { useSelector, useDispatch, connect } from 'react-redux'; import _ from 'lodash'; import {makeStyles, useTheme} from '@material-ui/core/styles'; import usePrevious from '../hooks/usePrevious'; import NotificationList from './NotificationList'; import { notificationsStateUpdate } from '../actions';  export default function Notifications(props) {  const [newNotifications, setNewNotifications] = useState([]);  const users = useSelector(state =gt; state.users);  const notificationClicked = useSelector(state =gt; state.notificationClicked)  const prevUsers = usePrevious(users);  const dispatch = useDispatch();  console.log('inside', users);   const isEqual = _.isEqual(prevUsers, users);  const timestamp = !isEqual ? new Date().getTime() : new Date("1991-09-24").getTime();   useEffect(() =gt; {  const notifications = [];  console.log('users', users);  users.forEach((user) =gt; {  if (user.uid === props.uid amp;amp; user.posts) {   user.posts.forEach((postContent) =gt; {  const likes = postContent.like ? Object.values(postContent.like) : null  const comments = postContent.comments_text ? Object.values(postContent.comments_text) : null   if (likes){  let filtererdLikes = likes.filter(post =gt; {  return post.like_notification === false  })  notifications.push(filtererdLikes)  }   if (comments){  let letfilteredComments = comments.filter(post =gt; {  return post.comment_notification === false  })  notifications.push(letfilteredComments)  }   })  }  });  const notificationsDataClean = notifications.flat(Infinity)  setNewNotifications(notificationsDataClean);  }, [timestamp]);   const useStyles = makeStyles((theme) =gt; ({  body: {  margin: '25',  background: '#3f51b5'  },  iconButton: {  position: 'relative',  display: 'flex',  alignItems: 'center',  justifyContent: 'center',  width: 50,  height: 50,  color: '#333333',  background: '#dddddd',  border: 'none',  outline: 'none',  borderRadius: '50%',  'amp;:hover': {  cursor: 'pointer'  },  'amp;:active': {  background: '#cccccc'  }  },  iconButton__badge: {  position: 'absolute',  top: -10,  right: -10,  width: 25,  height: 25,  background: 'red',  color: '#ffffff',  display: 'flex',  justifyContent: 'center',  alignItems: 'center',  borderRadius: '50%'  } } ));  const classes = useStyles(); const theme = useTheme();   return (  lt;divgt;  lt;headgt;  lt;meta charset="UTF-8" /gt;  lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /gt;  lt;titlegt;Icon Button Notification Badgelt;/titlegt;  lt;link href="https://fonts.googleapis.com/icon?family=Material Icons" rel="stylesheet" /gt;  lt;/headgt;   lt;body className={classes.body}gt;  lt;button type="button" className={classes.iconButton}gt;  lt;span class="material-icons"gt;notificationslt;/spangt;  lt;span className={classes.iconButton__badge}gt;{newNotifications.length}lt;/spangt;  lt;/buttongt;  lt;/bodygt;  {notificationClicked ? lt;NotificationList notifications={newNotifications} /gt; dispatch(notificationsStateUpdate({newNotifications})) : null}  lt;/divgt;  ); }  

Комментарии:

1. Вы хотите отправить при монтировании компонента, если условие верно?

2. Да, это было бы целью

Ответ №1:

Если я правильно понимаю, это должно сработать

 lt;NotificationList   notificationClicked, // pass in as prop instead of a ternary  notifications={newNotifications} /gt;     

затем позвоните своему диспетчеру в useEffect в списке уведомлений

 lt;NotificationListgt; /////  useEffect =(() =gt; {  //Whatever else  if (notificationClicked) {  dispatch(notificationsStateUpdate({newNotifications}))  }      },[notificationClicked])