【发布时间】:2017-12-21 01:38:49
【问题描述】:
更新好的,所以我注意到,即使在 isCategoryActive() 函数中,我只改变了变量 newCategories,它被分配了来自 @ 的值987654323@ 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] 博客?categories=1
[4] 博客?categories=4
[10] 博客?categories=10
但目前它会记录:
[1] 博客?categories=1
[1,4] 博客?categories=1,4
[1,4,10] blog?categories=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
【问题讨论】:
标签: javascript arrays reactjs dictionary pure-function