我正在尝试实现反应本机搜索过滤器。我在父屏幕上放置了数据数组,并在父文件上应用了搜索过滤器,并将过滤后的数据数组作为道具传递给了子屏幕。但是没有过滤器发生。我感到困惑或不知道我在做什么错。我有以下代码:
ParentScreen.js
import SearchInput, { createFilter } from 'react-native-search-filter';
...
const KEYS_TO_FILTERS = ['title']
export default class ProductScreen extends Component {
constructor(props) {
super(props)
this.state = {
items: API,
searchTerm: '',
}
}
searchUpdated(term) {
this.setState({ searchTerm: term })
}
render() {
const filteredItems = this.state.items.filter(createFilter(this.state.searchTerm, KEYS_TO_FILTERS))
let cardGridWithBodyProps = {
navigation: this.props.navigation,
api: filteredItems,
gridNumber: 2,
}
return (
<Container>
<ScrollView showsVerticalScrollIndicator={false}>
<View>
<Header>
<SearchInput
onChangeText={(term) => { this.searchUpdated(term) }}
placeholder="Search"
/>
</Header>
</View>
<View>
<CardGridWithBody {...cardGridWithBodyProps} />
</View>
</ScrollView>
</Container>
)
}
}
ChildScreen.js
export default class CardGridWithBody extends Component {
constructor(props) {
super(props)
this.state = {
items: this.props.api
}
}
renderGrid(gridArray) {
return gridArray.map((row, rowIndex) => (
<Row key={rowIndex}>
{row.map((col, colIndex) => (this.renderColumn(col, rowIndex,colIndex)))}
</Row>
));
}
renderColumn(colItem, rowIndex, colIndex) {
return (
<Col key={colIndex}>
<Text>{colItem.title}</Text>
</Col>
)
}
renderContent() {
let gridArray = this.state.items
return this.renderGrid(gridArray)
}
render() {
return (
this.renderContent()
)
}
}
答案 0 :(得分:1)
与其将数据保存为状态,不如直接从props访问它。如果将其保存为状态,则需要使用生命周期方法(例如shouldComponentUpdate或getDerivedStateFromProps
)进行手动更新renderContent = () => {
let gridArray = this.props.api;
return this.renderGrid(gridArray);
}
答案 1 :(得分:0)
在父屏幕中转换
searchUpdated(term) {
this.setState({ searchTerm: term })
}
到
searchUpdated = term => {
this.setState({ searchTerm: term })
}
在子组件中您可以执行
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.api !== prevState.api) {
return { api: nextProps.api };
}
return null;
}
componentDidUpdate(prevProps, prevState) {
if (
this.state.items !==
prevState.items
) {
this.setState({ items: api });
}
}