React 17:代码执行两次的问题



我有一个" presentational"组件:

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是一个简单的

import Select from 'react-select'
const Filter = (props) => {
return (
<Select
isMulti
options={props.options}
/>
)
}
export default Filter

我的麻烦是,我已经两次在控制台中打印tags对象,从formatTags函数得到。

为什么要执行两次?

谢谢

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

最新更新