更新OK,所以我注意到,即使在isCategoryActive()
函数中,我仅对从newCategories
分配了值的变量this.props.searchCategories
进行了变异,searchCategories
属性也更改了值,因此将其传递给连续数组项对isCategoryActive
函数的调用。为什么会发生?更新
我正在基于Wordpress REST API在React中构建博客的前端,在检查帖子类别是否已被过滤后,在创建链接以过滤帖子类别时遇到了问题。我遇到的问题是,即使我在map函数内编写了一个纯函数isCategoryActive
,每个连续的类别链接url中都有每个先前的类别id。我本以为在每次调用纯函数时,我都会收到干净的结果,但就我而言,事实并非如此。目前,wordpress存储3类:
ID为“未分类”:1
ID为4的“ javascript”
ID为“ 10”的“第三类”
我正在尝试使render()函数内的console.log(newCategories,url)函数进行记录:
[1]个博客?类别= 1
[4] Blog?categories = 4
[10] Blog?categories = 10
但目前它记录:
[1]个博客?类别= 1
[1,4]博客?类别= 1,4
[1,4,10]博客?类别= 1,4,10
我不知道为什么要保留以前的类别ID的记录。
这是代码:
// import dependencies
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import axios from 'axios'
// import components
import '../Styles/Css/PostsCategories.css'
import { createSearchUrl } from './SharedModules'
class PostsCategories extends Component {
constructor() {
super()
this.state = {
categories: null,
loading: false
}
}
componentDidMount() {
this.setState({
loading: true
})
axios.get(`http://localhost/wordpress-api/wp-json/wp/v2/categories`)
.then(res => {
this.setState({
categories: res.data,
loading: false
})
})
}
isCategoryActive = (category) => {
let newCategories = this.props.searchCategories
newCategories.indexOf(category) === -1
? newCategories.push(category)
: newCategories.splice(newCategories.indexOf(category),1)
return newCategories
}
render() {
if (this.state.loading || !this.state.categories) return <div className='posts-categories'><h2 className='loading'>Loading ...</h2></div>
const categories = this.state.categories.map(category => {
const newCategories = this.isCategoryActive(category.id)
const url = createSearchUrl('/blog', newCategories, this.props.searchString)
console.log(newCategories, url)
return (
<Link
to={url}
onClick={this.props.searchCategoryChange.bind(this, category.id)}
className='posts-category'
key={category.id} >
{category.name}
</Link>
)})
return (
<div className='posts-categories'>
{categories}
</div>
)
}
}
export default PostsCategories
最佳答案
在您的原始函数中有以下内容:
let newCategories = this.props.searchCategories
这实际上不会复制
searchCategories
,而是引用它。它们都指向同一个数组,这就是为什么还要修改原始searchCategories
数组的原因。当您映射
searchCategories
数组时(就像您在自己的解决方案中一样),您将在不修改searchCategories
数组的情况下构建新数组(使用push语句)。但是,这是制作阵列副本的一种非常复杂的方法。