文本框值未传递给 api 调用

我按照以下链接尝试做一个 poc https://www.reddit.com/r/reactjs/comments/82mxz3/how_to_make_an_api_call_on_props_change


在 Searchbar 中,我创建了一个文本框,当我提供 componentWillRecieveProps 并打印值以将其传递给 api 但没有打印时,我正在获取值但在 index.js 中。你能告诉我如何修复它吗?在下面提供更新的代码沙箱和代码片段。


https://codesandbox.io/s/eloquent-galielo-14874


//import React from "react";

import ReactDOM from "react-dom";

import React, { Fragment, useState, Component } from "react";


import "./styles.css";




class SearchBar extends Component {

  state = {

    groupCheckBoxValues: [],

    groupRadioValue: "PRO"

  };


  getInitialState() {

    return { value: "Hello!" };

  }

  handleChange(event) {

    console.log("handleChange", event.target.value);


    this.setState({ value: event.target.value });

  }


  componentWillReceiveProps({ search }) {

    console.log(search);

  }


  componentDidMount() {

    this.fetchdata("story");

  }


  fetchdata(type = "", search_tag = "") {

    var url = "https://hn.algolia.com/api/v1/search?tags=";

    fetch(`${url}${type}&query=${search_tag}`)

      .then(res => res.json())

      .then(data => {

        this.props.getData(data.hits);

      });

  }


  render() {

    return (

      <input

        type="text"

        value={this.state.value}

        onChange={this.handleChange}

      />

    );

  }

}


export default SearchBar;


缥缈止盈
浏览 127回答 1
1回答

弑天下

您实际上并未将文本输入的值传递给提取请求。我推荐这样的东西:class SearchBar extends Component {&nbsp; searchByKeyword = ({target}) => {&nbsp; &nbsp; await this.getQuery("story", target.value)&nbsp; }&nbsp; async componentDidMount() {&nbsp; &nbsp; await this.getQuery("story", "butts");&nbsp; }&nbsp; getQuery = async(type = "", search_tag = "") => {&nbsp; &nbsp; var url = "https://hn.algolia.com/api/v1/search?tags=";&nbsp; &nbsp; const resp = await fetch(`${url}${type}&query=${search_tag}`)&nbsp; &nbsp; return resp.json()&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp; &nbsp; &nbsp; &nbsp; onChange={this.searchByKeyword}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; );&nbsp; }}我删除了状态和事物,因为它似乎与问题并不完全相关。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript