首页 > 解决方案 > 如何在没有“onClick”的情况下调度 Redux 操作?

问题描述

对于下面的代码行,我如何调度notificationsStateUpdate没有onClick?如果为真,我希望这个动作被调度notificationClicked,所以我目前设置了一个三元表达式。

但是,我似乎无法使语法正常工作。在这种情况下可以调度吗?

{notificationClicked ?  
<NotificationList 
    notifications={newNotifications} /> 
    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 => state.users);
  const notificationClicked = useSelector(state => 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(() => {
    const notifications = [];
    console.log('users', users);
    users.forEach((user) => {
      if (user.uid === props.uid && user.posts) {

        user.posts.forEach((postContent) => {
              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 => {
                  return post.like_notification === false
                })
                notifications.push(filtererdLikes)
              }

              if (comments){
                let letfilteredComments = comments.filter(post => {
                  return post.comment_notification === false
                })
                notifications.push(letfilteredComments)
              }

        })
      }
    });
    const notificationsDataClean = notifications.flat(Infinity)
    setNewNotifications(notificationsDataClean);
  }, [timestamp]);

  const useStyles = makeStyles((theme) => ({
    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%',
      '&:hover': {
        cursor: 'pointer'
      },
      '&: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 (
    <div>
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Icon Button Notification Badge</title>
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
      </head>

      <body className={classes.body}>
        <button type="button" className={classes.iconButton}>
          <span class="material-icons">notifications</span>
          <span className={classes.iconButton__badge}>{newNotifications.length}</span>
        </button>
      </body>
      {notificationClicked ?  <NotificationList notifications={newNotifications} /> dispatch(notificationsStateUpdate({newNotifications})) : null}
    </div>
  );
}

标签: reduxreact-redux

解决方案


如果我理解正确,这应该有效

<NotificationList 
    notificationClicked, // pass in as prop instead of a ternary
    notifications={newNotifications} /> 
    

然后在 NotificationList 的 useEffect 中调用您的调度

<NotificationList>
/////
   useEffect =(() => {
        //Whatever else
    if (notificationClicked) {
    dispatch(notificationsStateUpdate({newNotifications}))
    }
    
         
 },[notificationClicked])

推荐阅读