尝试使用 react 和 Reddit API 显示搜索历史



我正在尝试将reddit API与react一起使用,以便当用户查找subreddit时,它将显示来自该subreddit的所有线程以及其他信息。我正在尝试合并一个历史记录功能,该功能将显示用户历史记录,并允许用户在单击以前的搜索之一时显示该搜索的信息。为了做到这一点,我创建了一个数组的状态变量,该变量将包含所有用户以前的搜索和一个名为 history 的组件,该组件将获取此数组并将所有搜索显示为可单击的按钮。但是,当我尝试导入我的历史记录组件时,我收到一条错误消息,指出"./History"不包含默认导出,即使它包含默认导出,我也不知道为什么。 这是应用程序.js:

import History from './History/History';
class App extends React.Component{
constructor(){
super();
this.state={
threads: [],
loading:false,
previousSearch: []
};
}
handleSearch = async (searchValue) => {
this.setState({ loading: true });
let [threads] = await Promise.all([
getThreads(searchValue)   
]);
console.log(searchValue)
this.setState({ threads, loading: false, previousSearch:this.state.previousSearch.concat(searchValue)});
}
render(){
return (
<div>
<SearchForm onSearch={this.handleSearch}/>
{this.state.loading && <Loading />}
<History previousSearches={this.state.previousSearch}/>
<div>
<ThreadList threads={this.state.threads}/>
</div>
</div>
);
}
}

这是历史.js:

import React from 'react'
export default function History(props){
{props.previousSearches.map((term) => {
return (
<button type="button" onClick={this.applyPreviousSearch.bind(this, term)}>
{term}
</button>
);
})}
}

我认为历史记录中存在错误.js

这就是它应该的样子

export default function History(props) {
return props.previousSearches.map((term) => {
return (
<button type="button" onClick={this.applyPreviousSearch.bind(this, term)}>
{term}
</button>
);
})
}

还要注意绑定它,因为它取决于上下文,而且在运行时理解它对我来说并不简单。

你需要从历史记录中返回.js。

import React from 'react';
export default function History(props)  {
return props.previousSearches.map((term) => { 
return (
<button type="button" onClick={this.applyPreviousSearch.bind(this, term)}> {term} </button> 
); 
});
}

我只是想插话说,除了 Sergio 所说的之外,如果 IDE 给您意外的错误消息,重新启动 IDE 有时会有所帮助。有时,IDE 的错误检查会崩溃/缓存或停止正常运行,重新启动会有所帮助。

最新更新