我正在使用React建立一个网站。在页面之一上,用户可以查看所有用户的个人资料并选择标签以对其进行过滤。除了选择的标签外,我还保留在组件状态下显示的其他功能用户列表。因此,当用户单击或取消单击标签时,不仅将更改标签列表(称为“过滤器”),而且还将更改当前显示的用户的个人资料(称为“ currentprofilelist”)。下面是我实现该功能的代码:当用户单击标记时,将调用“ updateTasks”,该标记将调用“ onlyFilters”以更改状态中的“ filters”字段。然后,“ onlyFilters”返回新的过滤器,该过滤器将传递到filtersUpdateList以修改状态中的“ currentprofilelist”。我收到错误消息:“未处理的拒绝(TypeError):this.onlyFilters(...)。然后不是函数” ,我想知道如何解决它。我尝试在其之前添加“ return”,但仍然无法正常工作。感谢您的耐心等待!
const filters = [
......
]
state = {
......
filters: [],
currentprofilelist: []
}
componentDidMount() {
const { users } = this.props;
this.setState({
currentprofilelist: users
})
}
......
onlyFilters = (e) => {
if (e.target.className === "unselected-button") {
const helper = this.state.filters;
helper.push(e.target.id);
this.setState({ filters : helper });
e.target.className = "selected-button";
return helper;
}
else {
const newfilters = this.state.filters.filter(tag => tag !== e.target.id);
this.setState({ filters : newfilters });
e.target.className = "unselected-button";
return newfilters;
}
}
filtersUpdateList = (newfilters) => {
const { users } = this.props;
var newprofilelist = [];
var i = 0;
while (i < users.length) {
if (newfilters.every(t => users[i].profile.areas_of_interest && users[i].profile.areas_of_interest.includes(t))) {
newprofilelist.push(users[i].id);
}
}
this.setState({currentprofilelist: newprofilelist});
}
updateFilters = async (e) => {
e.preventDefault();
this.onlyFilters(e)
.then((newfilters) => {
this.filtersUpdateList(newfilters);
})
}
......
render() {
const { auth, users, profile } = this.props;
return (
......
<Container fluid style={{ marginLeft:"70px", display: "flex", alignItems: "center", zIndex: "-1"}}>
<div className="filter-container">
<li>Filter by interests!</li>
<div className="form-inline">
{filters.map(filter => {
return (
<div className="unselected-button" id={filter} onClick={this.updateFilters}>
{filter}
</div>
);
})}
</div>
</div>
......
</Container>
......
);
}
}
const mapStateToProps = (state) => {
return {
users: state.firestore.ordered.users,
auth: state.firebase.auth,
profile: state.firebase.profile
}
}
......
答案 0 :(得分:1)
您的onlyFilters方法应该是异步函数,以便将其结果与promise一起使用,因此请尝试像这样声明它:
onlyFilters = async () => {....}
或
async onlyFilters() {....}