【问题标题】:How to set an initial API call in react ES6如何在 React ES6 中设置初始 API 调用
【发布时间】:2017-10-10 03:14:35
【问题描述】:

所以问题如下:我有一个搜索函数,它获取的是从另一个地方传递的默认值,搜索有效,但只有当它获得新输入时,因此如果我传递“Dress”它不会在我更改输入内容之前调用我的 api 函数。

我已经尝试了 setInitialState() 之类的所有方法,但没有任何显着的成功。

如您所见,我从 Searchbar 获得了一个 onTermChange,它被传递给 handleTermChange,然后更新我的产品:[],但我需要 this.props.location.query 作为默认搜索词,因为这是传递的变量。

  handleTermChange = (term)  => {
    const url = `http://localhost:3001/products?title=${term.replace(/\s/g, '+')}`;
    request.get(url, (err, res) =>  {
       this.setState({ products: res.body })
    });
  };

render () {
    return (
        <div className='col-md-12' style={{ margin: '0 auto' }}>
            <div className='row searchPageHeader' style={{ padding: '10px', backgroundColor: '#1ABC9C' }}/>
            <SideMenu />
            <SearchBar    onTermChange={this.handleTermChange}
                          defaultValue={this.props.location.query}/>
            <ProductList  products={this.state.products}
                          onProductSelect={selectedProduct => this.openModal(selectedProduct)}/>
            <ProductModal modalIsOpen={this.state.modalIsOpen}
                          selectedProduct={this.state.selectedProduct}
                          onRequestClose={ () => this.closeModal() }/>
            <Footer />
        </div>
       );
}

【问题讨论】:

  • 所以你想在组件挂载时自动执行location.query值的搜索?
  • 是的,我想自动将我的 products 设置为等于通过 location.query 传递的字符串,所以我的位置查询基本上应该通过handleTermChange 并更新我的产品列表

标签: reactjs


【解决方案1】:

我个人会在componentDidMount() 中执行相同的逻辑,如下所示:

componentDidMount () {
  const url = `http://localhost:3001/products?title=${this.props.location.query}`;
  request.get(url, (err, res) =>  {
    this.setState({ products: res.body })
  });
}

请注意,由于您正在执行异步调用 products 不会从 API 结果中填充,直到组件安装后的片刻。确保在 initialState 中初始化 products我假设这会返回一个数组,所以将其初始化为一个空数组)。


意见:由于您遵循事件处理程序命名约定(即onX 后跟handleX),我会避免在componentDidMount() 内调用handleTermChange(),因为函数名称表明它已绑定到事件监听器。因此,在我看来,直接调用它只是不好的做法。所以如果你宁愿在这里调用一个函数,而不是像我上面那样写出逻辑,我会做以下事情:

componentDidMount() {
  this.changeTerm(this.props.location.query);
}

changeTerm = (term)  => {
  const url = `http://localhost:3001/products?title=${term.replace(/\s/g, '+')}`;
  request.get(url, (err, res) =>  {
    this.setState({ products: res.body })
  });
};

handleTermChange = (term) => {
  this.changeTerm(term);
}

您的render() 保持不变。也许有点牵强,但我更喜欢这种方式。

【讨论】:

  • 执行您建议的操作时出现“term.replace 不是函数”错误
  • @Sjohansen,这可能是因为term 不是字符串。仔细检查您是否通过了this.props.location.query。在您的render 中进行控制台检查。
  • 我的错误,我的 this.props.location.query 返回了一个带有字符串 q 的对象,所以当我更改它时,它开始工作.谢谢!
  • 只是一个快速的最佳实践问题:将大部分函数调用移动到我的搜索函数中而不是将它们放在我的路由中是否有意义?
  • 很难回答。它们是什么功能?
猜你喜欢
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2021-12-29
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多