首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React 17:代码执行两次时出现问题

React 17:代码执行两次时出现问题
EN

Stack Overflow用户
提问于 2021-08-18 15:25:40
回答 1查看 43关注 0票数 0

我有一个“表现性”的部分:

代码语言:javascript
复制
import { Fragment, useEffect } from 'react'
import { Card, Col, Row } from 'react-bootstrap'
import { connect } from "react-redux"
import Filter from '../common/Filter'
import { actions as tagsActions } from "../../actions/TagsActions"

export const DocumentsPresentational = props => {

    const { fetchTags } = props

    useEffect(() => {
        fetchTags()
    }, [fetchTags])

    const formatTags = () => {
        let tags = null
        if (props.tags && props.tags.length > 0) {
            tags = props.tags.map(function(item) {
                return {
                    label: item.key,
                    value: item.key
                }
            })
        }
        return tags
    }

    return (
        <Fragment>
            <Row>
                <Col><h1 className="h3 mb-4 text-gray-800">Documenti</h1></Col>
            </Row>
            <Card>
                <Card.Body>
                    <Row>
                        <Col md={4}>
                            <p>Tags</p>
                            <Filter
                                options={formatTags()}
                            />
                        </Col>
                    </Row>
                </Card.Body>
            </Card>
        </Fragment>
    )
}

const mapStateToProps = state => {
    return {
        isLoading: state.documents.isLoading,
        items: state.documents.items,
        item: state.documents.item,
        total: state.documents.total,
        idItem: state.documents.idItem,
        feedbackSuccess: state.documents.feedbackSuccess,
        feedbackError: state.documents.feedbackError,
        showModalDetail: state.documents.showModalDetail,
        closeModalDetail: state.documents.closeModalDetail,
        tags: state.tags.items,
    }
}

const mapDispatchToProps = dispatch => {
    return {
        fetchTags: (orderBy, orderWay, page, perPage) => dispatch(tagsActions.fetchItems(orderBy, orderWay, page, perPage)),
    }
}
  

export default connect(
    mapStateToProps,
    mapDispatchToProps,
)(DocumentsPresentational)

Filter是一个简单的

代码语言:javascript
复制
import Select from 'react-select'

const Filter = (props) => {

    return (
        <Select
            isMulti
            options={props.options}
        />
    )
}

export default Filter

我的问题是,我在console中两次打印了从formatTags函数获得的tags对象。

为什么要执行两次?

谢谢

EN

回答 1

Stack Overflow用户

发布于 2021-08-18 17:03:59

在DocumentsPresentational组件中,您已经调用了fetchTags两次。useEffect在初始渲染时运行fetchTags。然后,在Select component中调用fetchTags。如果fetchTags是一个网络或cpu密集型函数,那么您可以只在useEffect中调用它一次,并将其返回的数据签名为状态变量,然后传递给Select component。

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

https://stackoverflow.com/questions/68835226

复制
相关文章

相似问题

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