javascript - 将变量传递给 componentDidMount

标签 javascript reactjs

我正在尝试更新 componentdidmount 中的 fetch API 调用以匹配 React 中的输入,但我很难将输入传递到 URl 的模板文字中。有人可以解释一下吗?

代码-

search(x) {
        console.log(this.state);
        console.log(x);
    }

    async componentDidMount() {
        let food = 'cheese';
        const url = `https://edamam-food-and-grocery-database.p.rapidapi.com/parser?ingr=${food}`;
        fetch(url, {
            method: 'GET',
            headers: {
                'x-rapidapi-host': 'edamam-food-and-grocery-database.p.rapidapi.com',
                'x-rapidapi-key': 'removed for privacy'
            }
        })
            .then((response) => response.json())
            .then((data) => console.log(data.hints));
    }

最佳答案

看起来您可能正在尝试做这样的事情。关键是 componentDidUpdate 响应状态的任何更改,因此如果您使用输入中的新值更新状态,它将运行。

class Thing extends React.Component {

  constructor(props) {
    super(props);

    // Set up the state with food and data properties
    this.state = { food: '', data: [] };
    this.handleSearch = this.handleSearch.bind(this);
  }

  // Have a separate method for your API call that can
  // grab the food from state and build then endpoint
  doApiCall () {
    const { food } = this.state;
    return fetch(`https://something.com/${food}`);
  }

  // componentDidUpdate is called after
  // a state change call. It calls the api method and then
  // updates the state with the data
  async componentDidUpdate() {
    const response = await this.doApiCall();
    const data = await reponse.json();
    this.setState({ data });
  }

  // When the input is changed, update the state
  // (which causes componentDidUpdate to run)
  handleSearch(e) {
    const { target: { value } } = e;
    this.setState({ food: value });
  }

  render () {

    return (
      <div>
        <input type="string" onChange={this.handleSearch} />
      </div>
     );

  }

}

关于javascript - 将变量传递给 componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60775759/

相关文章:

php - 禁止用户按后退或刷新

javascript - 如何使用 jQuery 添加 ul 元素自定义事件?

javascript - 使用 jquery 或 javascript 将文本复制到剪贴板

javascript - react 警告消除警告: Each child in a list should have a unique "key" prop

javascript - JavaScript 中重量(公斤)的正则表达式

javascript - Pixlr API 集成

javascript - 如何从对象中的 forEach 中获取搜索结果?

javascript - then 函数在所有异步调用执行之前执行

reactjs - Mantine DatePickerInput 渲染错误

javascript - 胜利图 - 布局问题