gpt4 book ai didi

javascript - 如何通过搜索栏 React Native 搜索 FlatList?

转载 作者:行者123 更新时间:2023-11-29 15:57:42 25 4
gpt4 key购买 nike

我有一个通过 Expo 构建的 React Native 应用程序,我想添加一个搜索功能来使用 React Native 中的搜索栏搜索 FlatList。下面的搜索栏来自 React Native Paper。

这是我的代码 (App.js):

constructor(props) {
super(props);
this.state = {
dataSource: []
}
}

state = {
firstQuery: '',
};

componentDidMount() {
const url = '// My URL'
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson.product
})
})
.catch((error) => {
console.log(error)
})
}

state = {
search: '',
};

updateSearch = search => {
this.setState({ search });
};

SearchFilterFunction(text) {
const newData = this.dataSource.filter(function(item) {
const itemData = item.name ? item.name.toUpperCase() : ''.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({
dataSource: newData,
text: text,
});
}

render() {
const { search } = this.state;
const { firstQuery } = this.state;
return (
<Searchbar
placeholder="Search"
onChangeText={query => {text => this.SearchFilterFunction(text)}}
value={firstQuery} />

<FlatList
data={this.state.dataSource}
renderItem={this.renderItem} />

);
}
}

我需要设置更多的默认状态吗? isLoadingerror: null 是否必要?我做错了什么?

更新现在这是我的 App.js:

constructor(props) {
super(props);
this.state = {
isLoading: true,
text: '',
dataSource: []
};
this.arrayholder = [];
}

state = {
firstQuery: '',
};

componentDidMount() {
const url = '// My URL'
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.product
}, {
function() {
this.arrayholder = responseJson;
}
}
)
})
.catch((error) => {
console.log(error)
})
}

state = {
search: '',
};

updateSearch = search => {
this.setState({ search });
};

SearchFilterFunction(text) {
const newData = this.dataSource.filter(function(item) {
const itemData = item.name ? item.name.toUpperCase() : ''.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({
dataSource: newData,
text: text,
});
}

renderItem = ({item}) => {
return (
// Code
);
}

render() {
return (
<Searchbar
placeholder="Search"
onChangeText={query => {text => this.SearchFilterFunction(text)}}
value={this.state.text} />
);
}

它给我一个“不变违规:作为回调传递的参数无效”。期待一个功能。而是收到:[object Object]'

最佳答案

您需要告诉 flatlist 如果 ABC 状态变量发生变化,则在源中查找数据变化并重新渲染。否则,它不会使用新值。

所以,告诉你需要传递一个 Prop extraData

<FlatList
extraData={this.state.dataSource}
data={this.state.dataSource}
renderItem={this.renderItem} />

现在,如果 dataSource 发生任何变化,flatlist 将重新呈现其内容

关于javascript - 如何通过搜索栏 React Native 搜索 FlatList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57086677/

25 4 0