【发布时间】:2019-06-07 22:02:47
【问题描述】:
我已经设置了一个搜索栏作为子组件,并传递了两个道具,一个是我正在渲染的卡片数组,另一个是函数,它应该随着搜索字段的变化而设置状态。
<Searchbar quesCards={questionCards} filter={this.filter} /> :
现在这个questionCards 是一个包含要显示的卡片数组的状态变量。
questionCards.push(
<QuestionCard
id={i}
question={question.question}
answer={question.answer}
isMarked={question.isMarked}
isPublished={question.isPublished}
validity={question.validity}
category={question.category}
/>
)
this.setState({ questionCards, newCards: questionCards, loading: false });
这里<QuestionCard /> 是另一个组件,但我相信它与问题无关。
在我的子组件中,我调用this.props.filter,过滤结果如下:
handleChange = name => event => {
//filtering the data ...
this.props.filter(newCards);
}
这是我在<Searchbar/>的onChange函数里面做的
回到父组件,
filter = (newCards) => {
console.log(newCards); //displays the desired result
this.setState({ newCards }); //the state changes, but is not rendered on screen
}
在这个 setState 之后,组件应该用新的结果重新渲染。但事实并非如此。
请注意,显示的是newCards,因为开头和questionCards仅用于传递prop
我已经尝试过this.forceUpdate
另外,如果我在函数 filter 内进行控制台日志,newCards 包含正确的结果,但在 this.setState({ newCards }) 之后没有重新渲染
【问题讨论】:
-
那么searchBar组件接受了一系列问题,过滤器是做什么的呢?按属性过滤?
-
搜索栏根据问题和搜索栏中的输入过滤结果。
ques.includes(event.target.value.toLowerCase());
另一方面,prop过滤器用于函数。如您所见,filter={this.filter}。所以this.props.filter(newCards)调用函数filter回到父组件中 -
如果您将过滤器发送回来,它会过滤数组还是重新查询?
-
过滤全部在子组件中进行,过滤后的结果作为参数传递给函数,准备在父组件中设置状态
标签: javascript reactjs