首页 > 解决方案 > React Api 调用:仅显示第一个 onSubmit 但之后什么也没有

问题描述

我有两个组件,带有调用 API 以获取价格的硬币道具的 CryptoPrice,以及我搜索硬币的 Nav,它呈现 CryptoPrice 组件,将 onSubmit 值分配给 CryptoPrice 硬币道具。

在我从 Nav 执行第二次 onSubmit 之前,显示效果很好。当我第二次 onSubmit 时,没有任何变化。

App.js 代码:

import CryptoPrice from "./components/CryptoPrice";
import Nav from "./components/Nav";
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Crypto Prices</h1>
        <div className="flex">
          <CryptoPrice coin="bitcoin" />
          <CryptoPrice coin="ethereum" />
        </div>
        <div>
          <Nav></Nav>
        </div>
      </header>
    </div>
  );
}

CryptoPrice 组件:

import styles from "./css/CryptoPrice.module.css";
export default class CryptoPrice extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      price: [],
      url: `https://api.coingecko.com/api/v3/simple/price?ids=${this.props.coin}&vs_currencies=usd`,
    };
  }
  componentDidMount = () => {
    this.loadData();
    setInterval(this.loadData, 20000);
  };

  loadData = () => {
    fetch(this.state.url)
      .then((response) => response.json())
      .then((data) => {
        let key = Object.keys(data);
        return data[key];
      })
      .then((coin) => {
        let price = coin.usd;
        this.setState({ price });
      });
  };

  render() {
    return (
      <div className={styles.padding}>
        <h2>{this.props.coin} price</h2>
        <div>{this.state.price}$</div>
      </div>
    );
  }
}

导航组件

import CryptoPrice from "./CryptoPrice";
export default class Nav extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      coin: "",
      isSubmitted: false,
    };
  }

  componentDidMount() {
    this.setState({ isSubmitted: false });
  }

  render() {
    return (
      <div>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            this.setState({ isSubmitted: true });
          }}
        >
          <input
            type="text"
            onChange={(e) => {
              this.setState({ coin: e.target.value });
            }}
          ></input>
          <input type="submit" value="Add"></input>
        </form>

        {this.state.isSubmitted && <CryptoPrice coin={this.state.coin} />}
      </div>
    );
  }
}

非常感谢任何帮助/反馈

标签: reactjs

解决方案


您的问题是因为您将 url 设置为 state,因此当 props 更新时它不会更新。尝试将您的 fetch 函数更改为直接使用道具(还记得在卸载时清除 setInterval):

      loadData = () => {
        fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${this.props.coin}&vs_currencies=usd`)
      .then((response) => response.json())
      .then((data) => {
        let key = Object.keys(data);
        return data[key];
      })
      .then((coin) => {
        let price = coin.usd;
        this.setState({ price });
      });
  };

推荐阅读