【问题标题】:Trying to display search history with react and the Reddit API尝试使用 react 和 Reddit API 显示搜索历史
【发布时间】:2019-09-22 20:31:30
【问题描述】:

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

这里是 History.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>
  );
})}
}

【问题讨论】:

  • 请不要破坏您的帖子。如果您的帖子有问题需要删除(并且您不能自己删除,因为已经有答案),请标记它以引起版主注意并说明原因。
  • 你的问题标题是什么? "fffffffffffffffffff"是什么意思
  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange (SE) 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 SE 分发内容的不可撤销的权利(即无论您未来的选择如何)。根据 SE 政策,分发非破坏版本。因此,任何破坏行为都将被撤销。请参阅:How does deleting work? …。如果允许删除,则帖子下方左侧有一个“删除”按钮,但仅在浏览器中,而不是移动应用程序中。

标签: javascript reactjs


【解决方案1】:

我认为 History.js 中存在错误

应该是这样的

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

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

【讨论】:

    【解决方案2】:

    你需要从 History.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> 
              ); 
         });
     }
    

    【讨论】:

      【解决方案3】:

      我只是想补充一下,除了 Sergio 所说的,如果它给你一个意外的错误消息,重新启动你的 IDE 有时会有所帮助。有时 IDE 的错误检查会崩溃/缓存或停止正常运行,而重新启动会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-13
        • 2017-03-09
        • 2015-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-22
        • 2020-05-08
        相关资源
        最近更新 更多