reactjs - 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>
);
}
}
非常感谢任何帮助/反馈
解决方案
您的问题是因为您将 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 });
});
};
推荐阅读
- java - 通过API获取java进程的RSS内存使用情况
- typescript - 保留“keyof T”信息的 Object.entries?
- r - 如何使用 mult 消除 data.table 中的重复项
- javascript - 用于检索 WIX 数据库 JSON 文件的 Excel 中的 API
- sas - 在 SAS 中,如何从值中删除小数点?
- makefile - 根据文件的年龄在 Makefile 中运行不同的代码
- c++ - 为什么只有第一个循环在工作而休息不是?
- function - 文本字段中的函数定义(单击按钮后)
- r - 在数据框中特定字符后提取数字
- laravel - 我将 Laravel 与 Laratrust 一起使用,如何打印附加到帐户的角色?