2017-05-11 5 views
1

問題は次のとおりです。取得するデフォルトの値は別の場所から渡され、検索は機能しますが、新しい入力を取得した場合のみ私が「ドレス」を渡している場合は、入力の中で何かを変更する前に、私のAPI関数を呼び出すことはありません。反応するES6で最初のAPI呼び出しを設定する方法

setInitialState()のようなものを少し試しましたが、特に目立つことはありませんでした。

私はその後、私の製品を更新handleTermChangeに渡された私の検索バーからonTermChangeを取得しています見ることができるように:[]、私は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> 
     ); 
} 
+0

コンポーネントがマウントされたときに 'location.query'の値で検索を自動的に実行したいですか? – Chris

+0

はい、自動的に_products_を_location.query_を渡す文字列と同じに設定したいので、私のロケーションクエリは基本的にhandleTermChangeを実行してproductListを更新する必要があります – Sjohansen

答えて

1

私は個人的にちょうどこのようcomponentDidMount()で同じロジック、だろう:あなたは、非同期呼び出しを行っているので、productsが瞬間までAPIの結果から移入されないことを

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

注意をコンポーネントが取り付けられた後productsinitialStateに初期化することを確認してください(これは配列を返すと仮定しているため、空の配列として初期化します)。


意見:あなたは、イベントハンドラの命名規則に従っているので、関数名は、それがイベントリスナーにバインドされています示唆しているため(すなわちonXhandleX続く)私は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()は変わりません。たぶんストレッチですが、私はこれを好む方法です。

+0

「term.replaceは関数ではありません」エラー – Sjohansen

+0

@Sjohansenを提案したとき、それはおそらく 'term'が文字列ではないからです。 'this.props.location.query'を渡していることを再度確認してください。あなたの 'render'でコンソールをチェックして確認してください。 – Chris

+1

私の間違い、私の_this.props.location.query_は文字列_q_を持つオブジェクトを返しました。私がそれを変更したとき、それは動作し始めました。ありがとうございました! – Sjohansen

関連する問題