【问题标题】:Search Bar with API database带有 API 数据库的搜索栏
【发布时间】:2021-03-25 03:33:56
【问题描述】:
export class Diet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    };
  }

  updateSearch = (e) => {
    axios
      .get(
        `https://api.spoonacular.com/food/products/search?apiKey{1234}&query=${data}&number=100`
      )
      .then((res) => {
        this.setState({ data: res.data });
      })
      .catch((error) => {
        console.log(error.response.data);
      });
  };

  render() {
    return (
      <>
        <SearchBar
          placeholder="Search Food..."
          onChangeText={this.updateSearch}
          value={data}
        />
        <List style={{ paddingTop: hp("2%") }}>
          <TouchableOpacity>
            {this.state.data.map(({ type }) => (
              <Text>{this.state.type.products.title}</Text>
            ))}
          </TouchableOpacity>
        </List>
      </>
    );
  }
}

大家好,我正在尝试构建一个SearchBar,当我输入SearchBar 时,URL 中的变量query 应该更改为我正在输入的内容,现在当我运行它时它会返回什么都没有。

数据库文档链接:https://spoonacular.com/food-api/docs#Search-Grocery-Products

【问题讨论】:

    标签: reactjs react-native api search axios


    【解决方案1】:

    您对接收到的数据使用相同的状态并且在 SearchBar 中输入值,首先创建另一个状态以保留输入值并将其传递到 URL 中

    export class Diet extends Component {
      constructor(props) {
        super(props);
        this.state = {
          data: [],
          searchValue: '',
        };
      }
    
      updateSearch = (value) => {
        this.setState({searchValue: value})
        axios
          .get(
            `https://api.spoonacular.com/food/products/search?apiKey{1234}&query=${value}&number=100`
          )
          .then((res) => {
            this.setState({ data: res.data });
          })
          .catch((error) => {
            console.log(error.response.data);
          });
      };
    
      render() {
        return (
          <>
            <SearchBar
              placeholder="Search Food..."
              onChangeText={this.updateSearch}
              value={searchValue}
            />
            <List style={{ paddingTop: hp("2%") }}>
              <TouchableOpacity>
                {this.state.data.map(({ type }) => (
                  <Text>{this.state.type.products.title}</Text>
                ))}
              </TouchableOpacity>
            </List>
          </>
        );
      }
    }
    

    但是,不建议每次用户键入时都这样做,您可以查看此模式以消除 API 调用的抖动https://gist.github.com/simonw/c29de00c20fde731243cbac8568a3d7f

    更新

    由于API不允许搜索空值,所以当输入为空时,设置一个条件将数据设置为空数组

      updateSearch = (value) => {
        this.setState({searchValue: value})
        if(value.trim() !== '') {
          axios
            .get(
              `https://api.spoonacular.com/food/products/search?apiKey{1234}&query=${value}&number=100`
            )
            .then((res) => {
              this.setState({ data: res.data });
            })
            .catch((error) => {
              console.log(error.response.data);
            });
        } else {
          setState({data: []})
        }
      }; 
    

    【讨论】:

    • 它现在给了我一个不同的error: undefined is not a function (near'...this.state.data.map'),抱歉有很多问题,我是新手,还在学习。