首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将参数传递给不起作用的事件处理程序

将参数传递给不起作用的事件处理程序
EN

Stack Overflow用户
提问于 2019-03-13 02:30:39
回答 1查看 404关注 0票数 0

好吧,我有个刮头的地方我需要一点帮助。设置是用一个类别页面读取API中的类别列表,然后列出它们的React/Redux应用。那部分运作得很好。我要做的是将一个事件处理程序传递给每个类别子组件,当单击这些子组件时,这些组件会分派一个操作来切换组件的状态,也就是说,如果类别被选中并单击,它将“取消选择”它(这实际上意味着从一个名为user_category的数据库表中删除一个条目),如果没有被选中,将为该用户“选择”该类别(在user_category表中添加一个条目)。

因此,我有一个onclick处理程序(handleCatClick),它最终应该传递一个categoryId和一个userId来执行这些操作。不幸的是,我发现,即使这些参数被传递给函数,它们最终也是没有定义的。所以我不确定我是否正确地传递了这个函数,或者我漏掉了什么。

除了这个以外,一切都能正常工作--也许你能帮我发现问题;-)

单击此处查看数据库布局

单击此处查看类别页的外观。

我的应用程序中适用的页面:

该体系结构基本上如下所示:

代码语言:javascript
复制
/views/[Categories]
  - index.js (wrapper for the Categories Component)
  - CategoriesComponent.jsx (should be self-explanatory)
   [duck]
        - index.js   (just imports a couple of files & ties stuff together)
        - operations.js  (where my handleCatClick() method is)
        - types.js  (Redux constants)
        - actions.js  (Redux actions)
        - reducers.js   (Redux reducers)
   [components]
        [Category]
                 - index.jsx  (the individual Category component)

/views/index.js(主类别页面包装器)

代码语言:javascript
复制
import { connect } from 'react-redux';
import CategoriesComponent from './CategoriesComponent';
import { categoriesOperations } from './duck'; // operations.js



const mapStateToProps = state => {
    // current state properties passed down to LoginComponent (LoginComponent.js)
    const { categoryArray } = state.categories;
    return { categoryArray }
  };



  const mapDispatchToProps = (dispatch) => {
    // all passed in from LoginOperations (operations.js)
    const loadUserCategories = () => dispatch(categoriesOperations.loadUserCategories());
    const handleCatClick = () => dispatch(categoriesOperations.handleCatClick());
    return {
        loadUserCategories,
        handleCatClick
    }
  };


  const CategoriesContainer = connect(mapStateToProps,mapDispatchToProps)(CategoriesComponent);

  export default CategoriesContainer;

/views/CategoriesComponent.jsx (类别视图显示层)

代码语言:javascript
复制
import React from 'react';
import {Row,Col,Container, Form, Button} from 'react-bootstrap';
import {Link} from 'react-router-dom';
import './styles.scss';
import Category from './components/Category';
import shortid from 'shortid';

class CategoriesComponent extends React.Component {
    constructor(props) {
        super(props);
        this.loadUserCats = this.props.loadUserCategories;
        this.handleCatClick = this.props.handleCatClick;
    }

    componentWillMount() {
        this.loadUserCats();
    }

    render() {
        return (
            <Container fluid className="categories nopadding">
                <Row>
                    <Col xs={12}>
                    <div className="page-container">
                        <div className="title-container">
                            <h4>Pick your favorite categories to contine</h4>
                        </div>
                        <div className="content-container">
                            <div className="category-container">
                                {
                                    this.props.categoryArray.map((item) => {
                                        return <Category className="category" handleClick={this.props.handleCatClick} key={shortid.generate()} categoryData={item} />
                                    })
                                }
                            </div>
                        </div>
                    </div>
                    </Col>
                </Row>
            </Container>
        )        
    }
}


export default CategoriesComponent

/views/Categories/components/index.jsx (单类别组件)

代码语言:javascript
复制
import React from 'react';
import {Row,Col,Container, Form, Button} from 'react-bootstrap';
import './styles.scss';
import Img from 'react-image';

class Category extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            categoryName: this.props.categoryData.category_name,
            categoryImg: this.props.categoryData.category_img,
            categoryId: this.props.categoryData.category_id,
            userId: this.props.categoryData.user_id,
            selected: this.props.categoryData.user_id !== null,
            hoverState: ''
        }
        this.hover = this.hover.bind(this);
        this.hoverOff = this.hoverOff.bind(this);
        this.toggleCat = this.toggleCat.bind(this);
    }


    toggleCat() {

        // the onClick handler that is supposed to 
        // pass categoryId and userId.  When I do a 
        // console.log(categoryId, userId) these two values
        // show up no problem...

        const {categoryId, userId} = this.state;
        this.props.handleClick(categoryId, userId);
    }


    hover() {
        this.setState({
            hoverState: 'hover-on'
        });
    }

    hoverOff() {
        this.setState({
            hoverState: ''
        });
    }

    render() {
        const isSelected = (baseCat) => {
            if(this.state.selected) {
                return baseCat + " selected";
            }
            return baseCat;
        }
        return (
            <div className={"category" + ' ' + this.state.hoverState} onClick={this.toggleCat} onMouseOver={this.hover} onMouseOut={this.hoverOff}>
                <div className={this.state.selected ? "category-img selected" : "category-img"}>
                    <Img src={"/public/images/category/" + this.state.categoryImg} className="img-fluid" />
                </div>
                <div className="category-title">
                    <h5 className={this.state.selected ? "bg-primary" : "bg-secondary"}>{this.state.categoryName}</h5>
                </div>
            </div>
        );
    }
}
export default Category;

/views/Categories/duck/operations.js (我把它连接在一起的地方)

代码语言:javascript
复制
// operations.js
import fetch from 'cross-fetch';
import Actions from './actions';
import Config from '../../../../config';


const loadCategories = Actions.loadCats;
const selectCat = Actions.selectCat;
const unSelectCat = Actions.unSelectCat;

const localState = JSON.parse(localStorage.getItem('state'));
const userId = localState != null ? localState.userSession.userId : -1;



const loadUserCategories = () => {

        return dispatch => {
            return fetch(Config.API_ROOT + 'usercategories/' + userId)
            .then(response => response.json())
            .then(json => {
            dispatch(loadCategories(json));
            });
        }      
}


const handleCatClick = (categoryId, categoryUserId) => {

    // HERE IS WHERE I'M HAVING A PROBLEM:
    // for whatever reason, categoryId and categoryUserId
    // are undefined here even though I'm passing in the 
    // values in the Category component (see 'toggleCat' method)

    var params = {
        method: categoryUserId !== null ? 'delete' : 'post',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify(
            {
                "category_id": categoryId, 
                user_id: categoryUserId !== null ? categoryUserId : userId
            }
        )
    };

    const toDispatch = categoryUserId !== null ? unSelectCat : selectCat;
    return dispatch => {
        return fetch(Config.API_ROOT + 'usercategories/', params)
        .then(response => response.json())
        .then(json => {
            dispatch(toDispatch(json));
        });
    } 

}

export default {
    loadUserCategories,
    handleCatClick
}

我遇到的问题是:

所以我想我要么没有正确引用handleCatClick,要么我不知何故没有正确地传递categoryId和userId,所以当它最终到达operations.js中的handleCatClick(categoryId,categoryUserId)时,结果是没有定义的。可能是很简单的事,但我找不到。注意:我没有包括像types.js或reducers.js这样的文件,因为它们似乎超出了问题的范围,但是如果您需要它们,请告诉我。提前感谢您的帮助!

EN

回答 1

Stack Overflow用户

发布于 2019-03-13 02:56:42

尝试以下更改:向这些处理程序添加params

代码语言:javascript
复制
const handleCatClick = (categoryId, categoryUserId) => dispatch(categoriesOperations.handleCatClick(categoryId, categoryUserId));

代码语言:javascript
复制
return <Category className="category" handleClick={(categoryId, categoryUserId) => this.props.handleCatClick(categoryId, categoryUserId)} key={shortid.generate()} categoryData={item} />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55133455

复制
相关文章

相似问题

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