你好,我已经在这里停留了两天以上,并且一直在尝试,但是现在真的很困惑,需要咨询/帮助。
我正在开发一个带有搜索栏的create-react-app(使用Giphy API),当用户搜索gif时,它会呈现10 gif的样子。我添加了一个“排序”按钮,将gif从最新到最旧进行排序。现在,我尝试添加一个“清除过滤器”按钮,该按钮将重新渲染 之前的gif。这是我目前拥有的:
class App extends Component {
constructor() {
super();
this.state = {
query: '',
gifs: [],
isSearching: true,
isDataSorting: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.onSortByDate = this.onSortByDate.bind(this);
this.onClearFilter = this.onClearFilter.bind(this);
}
handleChange(evt) {
this.setState({ query: evt.target.value });
}
// ajax using axios to giphy searchendpoint happens here and is working
async handleSubmit(evt) {
evt.preventDefault();
try {
// AJAX here with API key
const { data } = await axios.get(searchEndpoint);
this.setState({
gifs: data.data,
isSearching: false,
isDataSorting: false
});
} catch(err) {
console.error(err);
}
this.setState({ query: '' });
}
// this method is working great
// when the sort btn is clicked isDataSorting becomes "true"
// and in AllGifs component I have a conditional statement that
// would render the sorted gifs (using utility/helper method)
// if "false," just renders how data/gifs comes in from endpoint
onSortByData() {
this.setState({ isDataSorting: !this.state.isDataSorting});
}
// I am stuck here... I want to "clear" the sort that happened with onSortByData()
onClearFilter() {
console.log('Clear was clicked!');
// initially, I had this hoping that it would re-render with
// isDataSorting as "false" in AllGifs component...
this.setState({ isDataSorting: false });
}
// isDataSorting, onSortByDate, and onClearFilter are all being
// passed down as props to my child component AllGifs
render() {...}
}
我被卡在onClearFilter()上。用户单击“排序”并且onSortByData()更改为true,并且该实用程序方法按最新到最旧的顺序对gif进行排序后,我希望用户单击“清除”并获得最初的接收数据顺序或数据之前“排序”。
非常感谢大家花时间阅读本文。 任何建议,技巧或帮助都非常棒!
答案 0 :(得分:1)
很难准确地找出问题所在,但我怀疑这个问题可能与您的排序方式有关。
渲染组件时,需要对GIF数组进行复制并对那个进行排序,而不是对状态对象进行排序。您将需要以下内容:
const renderedGIFs = this.state.gifs.slice()
然后,如果设置了相关标志,则对渲染的GIF进行排序。如果该标志为假,则数组将不排序地传递给render函数。但是至关重要的是,您的状态始终包含从Giphy获取的原始数组,这意味着您随时可以恢复到原始状态。