首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当我点击任何图标时,如何更新我的反应

当我点击任何图标时,如何更新我的反应
EN

Stack Overflow用户
提问于 2019-04-28 20:11:59
回答 1查看 41关注 0票数 1

我有一个组件,我正在使用redux管理状态,并使用新的map从redux存储访问该组件的数组数据。我需要能够让我的图标的值在点击时增加。我不确定如何访问我的反应的值来使其工作,并使用handleReactions处理我的单击事件

constants.js

代码语言:javascript
复制
/** @constant */
export const INITIAL_STATE = {
    uploads: new Map(),
};

export const USER_UPLOADS = [
    {
        _id: 0,      
        image: 'http://sugarweddings.com/files/styles/width-640/public/1.%20The%20Full%20Ankara%20Ball%20Wedding%20Gown%20@therealrhonkefella.PNG',
        reactions: {
            dislike: 0,
            like: 0,
            maybe: 0,
        },
        story: "It's my birthday next week! What do you think?",
        user: 'Chioma',
    },
    {
        _id: 1,        
        image: 'https://dailymedia.com.ng/wp-content/uploads/2018/10/7915550_img20181007141132_jpeg01c125e1588ffeee95a6f121c35cd378-1.jpg',
        reactions: {
            dislike: 0,
            like: 0,
            maybe: 0,
        },
        story: 'Going for an event. Do you like my outfit?',
        user: 'Simpcy',
    },
    {
        _id: 2,        
        image: 'https://i0.wp.com/www.od9jastyles.com/wp-content/uploads/2018/01/ankara-styles-ankara-styles-gown-ankara-tops-ankara-gowns-ankara-styles-pictures-latest-ankara-style-2018-latest-ankara-styles-ankara-ankara-styles.png?fit=437%2C544&ssl=1',
        reactions: {
            dislike: 0,
            like: 0,
            maybe: 0,
        },
        story: 'Saturdays are for weddings. Yay or nay?',
        user: 'Angela',
    },
];

actions.js

代码语言:javascript
复制
import { UPDATE_REACTION, REQUEST_UPLOAD_LIST } from './actionTypes';

/**
 * Triggers request to react on a post
 *
 * @function
 * @return {Object} The {@link actionTypes.REQUEST_UPLOAD_LIST REQUEST_UPLOAD_LIST}
 * action.
 */
export function updateReaction(itemid, reaction) {
    return {
        itemid,
        reaction,
        type: UPDATE_REACTION,
    };
}

/**
 * Triggers request for the lists of uploads
 *
 * @function
 * @return {Object} The {@link actionTypes.REQUEST_UPLOAD_LIST REQUEST_UPLOAD_LIST}
 * action.
 */
export const requestUploadList = payload => ({
    payload,
    type: REQUEST_UPLOAD_LIST,
});

reducers.js

代码语言:javascript
复制
import { UPDATE_REACTION, REQUEST_UPLOAD_LIST } from './actionTypes';
import { INITIAL_STATE, USER_UPLOADS } from './constants';

/**
 * Creates a Javascript Map with the user uploads mapped by id
 *
 * @param {Array} USER_UPLOADS - a users uploads
 * @return {Map} - the user uploads
 */

function generateUploadsMap() {
    const setOfUserUploads = new Map();

    USER_UPLOADS.forEach(userUpload => {
        const { _id } = userUpload;

        setOfUserUploads.set(_id, userUpload);
    });

    return setOfUserUploads;
}

function updateItemReactions(itemid, reaction, uploads) {
    const upload = uploads.get(itemid);
    upload.reactions = {
        ...upload.reactions,
        [reaction]: upload.reactions[reaction] + 1,
    };
    uploads.set(itemid, upload);
    return uploads;
}

console.log(updateItemReactions());
export default (state = { ...INITIAL_STATE }, action) => {
    switch (action.type) {
        case REQUEST_UPLOAD_LIST: {
            return {
                ...state,
                uploads: generateUploadsMap(),
            };
        }
        case UPDATE_REACTION: {
            const { uploads } = state;

            return {
                ...state,
                uploads: updateItemReactions(action.itemid, action.reaction, uploads),
            };
        }

        default:
            return state;
    }
};

home.js

代码语言:javascript
复制
import PropTypes from 'prop-types';
import React from 'react';
import { Avatar, Card, Icon, List } from 'antd';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import { LIST_TEXTS, STYLES } from '../constants';
import * as actions from '../actions';
import { getUploads } from '../selectors';

const { AVATAR, CARD_CONTAINER, CARD_LIST, ICON, USER_LIST } = STYLES;
const { INNER, MORE, UPLOAD, VERTICAL } = LIST_TEXTS;

const IconText = ({ type, text }) => (
    <span>
        <Icon type={type} style={ICON} />
        {text}
    </span>
);
function createReactionsIcon(item, updateReaction) {
    const { like, dislike, maybe } = item.reactions;
    const icons = [
        { reaction: 'like', text: `${like}`, type: 'heart' },
        { reaction: 'dislike', text: `${dislike}`, type: 'dislike' },
        { reaction: 'maybe', text: `${maybe}`, type: 'meh' },
    ];
    return icons.map(({ reaction, text, type }) => (
        <IconText
          onClick={updateReaction(item._id, reaction)}
          key={reaction}
          type={type}
          text={text}
        />
    ));
}

class Home extends React.Component {
    componentDidMount() {
        const { requestUploadList } = this.props.actions;

        requestUploadList();

    }

        updateReaction = (itemid, reaction) => {
        const { updateReaction } = this.props.actions;
        updateReaction(itemid, reaction);
    }

    render() {
        const { uploads } = this.props;
        const values = Array.from(uploads.values());

        return (
            <div style={CARD_CONTAINER}>
                <List
                  itemLayout={VERTICAL}
                  dataSource={values}
                  renderItem={item => (
                      <List.Item style={USER_LIST}>
                          <Card
                            actions={createReactionsIcon(item, this.updateReaction)}
                            cover={<img alt={UPLOAD} src={item.image} />}
                            extra={<Icon type={MORE} />}
                            hoverable
                            title={(
                                <a href="/">
                                    <Avatar src={item.image} style={AVATAR} />
                                    {item.user}
                                </a>
                            )}
                            type={INNER}
                            style={CARD_LIST}
                          >
                              {item.story}
                          </Card>
                      </List.Item>
                  )}
                />
            </div>
        );
    }
}

Home.propTypes = {
    uploads: PropTypes.instanceOf(Map),
    actions: PropTypes.object,
};

const mapStateToProps = state => ({
    uploads: getUploads(state),
});

const mapDispatchToProps = dispatch => ({
    actions: bindActionCreators(actions, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(Home);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-28 20:16:00

mapDispatchToProps中,您绑定了操作创建者,并为在Home组件中传递的actions属性设置了。

createReactionsIcon中生成的Icon元素不知道处理onClick事件的方法,除非给出一种将操作分派到redux-store以更新其反应的方法。

Home中,需要将actions.updateReactions转发到createReactionsIcon,并为其IconText注册onClick事件。

代码语言:javascript
复制
render() {
  //...
  <Card
    actions={createReactionsIcon(item, this.props.actions.updateReaction)}
  //...
}

createReactionsIcon中,

代码语言:javascript
复制
function createReactionsIcon(item, updateReaction) {
  const { like, dislike, maybe } = item.reactions;


  const icons = [
    { reaction: 'like', text: `${like}`, type: 'heart'},
    { reaction: 'dislike', text: `${dislike}`, type: 'dislike'},
    { reaction: 'maybe', text: `${maybe}`, type: 'meh'},
  ];
  //...
  return icons.map(({ reaction, text, type }) => (
    <IconText 
      onClick={() => updateReaction(item._id, reaction)} 
      key={reaction}
      type={type}
      text={text}
    />
  ));
}

在这里,应该修改actions.jsupdateReaction操作创建者的定义,以包括更多字段,如操作的items和reaction。

代码语言:javascript
复制
function updateReaction(itemid, reaction) {
  return {
    type: UPDATE_REACTION,
    itemid,
    reaction
  }
}

然后,使UPDATE_REACTION操作类型的reducer使用它来更新reducer.js中项目id的反应。

代码语言:javascript
复制
///...
case UPDATE_REACTION:
  const { uploads } = state;

  return {
    ...state,
      uploads: updateItemReaction(action.itemid, action.reaction, uploads),
    };
  }
///...

其中,updateItemReaction是定义为:

代码语言:javascript
复制
function updateItemReaction(itemid, reaction, uploads) {
  const upload = uploads.get(itemid)
  const uploadUpdate = {
    ...upload,
    reactions: {
      ...upload.reactions,
      [reaction]: upload.reactions[reaction] + 1
    }
  }

  uploads.set(itemid, uploadUpdate)
  return uploads;
}

现在使用

,而上面的方法是如何查看存储中的对象是一个Map。必须注意仅更新存储中已更改的部分,以便仅重新呈现使用该存储部分中的值的组件。

我强烈建议为您的组件状态使用不可变的数据结构,或者通过使用纯对象严格地将存储视为不可变的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55890121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档