【发布时间】:2019-02-01 19:34:46
【问题描述】:
我目前正在学习 react 和 redux,但偶然发现了一个我无法真正理解的问题。尝试实现相同的功能 如本文所示:https://medium.com/@yaoxiao1222/implementing-search-filter-a-list-on-redux-react-bb5de8d0a3ad 但即使来自我正在使用的其他 api 的数据请求成功,我也无法将组件中的本地状态分配给我的 redux-state,以便能够过滤我的结果。这是我的组件:
import React from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import * as fetchActions from '../../actions/fetchActions'
import Stafflist from './Stafflist'
class AboutPage extends React.Component {
constructor(props) {
super(props)
this.state = {
search: '',
currentlyDisplayed: this.props.store.posts
}
this.updateSearch = this.updateSearch.bind(this)
}
updateSearch(event) {
let newlyDisplayed = this.state.currentlyDisplayed.filter(
(post) => {
return (
post.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1
|| post.role.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1
)}
)
console.log(newlyDisplayed)
this.setState({
search: event.target.value.substr(0, 20),
currentlyDisplayed: newlyDisplayed
})
}
render() {
return (
<div className="about-page">
<h1>About</h1>
<input type="text"
value={this.state.search}
onChange={this.updateSearch}
/>
//component for rendering my list of posts.
<Stafflist posts={this.state.currentlyDisplayed} />
</div>
)
}
}
// this is here i assign my api data to this.props.store.posts
function mapStateToProps(state, ownProps) {
return {
store: state
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(fetchActions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AboutPage)
比较我如何将我的商店状态分配给我的本地组件与它在文章中的工作方式,它似乎以相同的方式完成。我的:
this.state = {
search: '',
currentlyDisplayed: this.props.store.posts
}
文章:
this.state = {
searchTerm: '',
currentlyDisplayed: this.props.people
}
在 react devtools 中,我可以看到我的数据,因为它应该在商店中,但是将它分配给组件中的本地状态以执行过滤是行不通的,我真的不知道如何调试这个。我在本地组件中的状态只是说
State
currentlyDisplayed: Array[0]
Empty array
如果我改变了
<Stafflist posts={this.state.currentlyDisplayed} />
到
<Stafflist posts={this.props.store.posts} />
列表按原样呈现:)
减速机:
import * as types from '../actions/actionTypes'
import initialState from './initialState'
export default function postReducer(state = initialState.posts, action) {
switch(action.type) {
case types.FETCH_POSTS_SUCCESS:
return action.posts.data.map(post => {
return {
id: post.id,
name: post.acf.name,
role: post.acf.role
}
})
default:
return state
}
}
有什么想法吗?
【问题讨论】:
-
我相信您在
this.currentlyDisplayed.filter中缺少state。应该是this.state.currentlyDisplayed.filter()
标签: javascript reactjs search filter redux