ReactJS如何将state中的字符串值嵌入API请求URL?
解决方案
核心问题:模板字符串语法错误
你当前的API URL用单引号包裹,而ES6模板字符串必须使用**反引号()**才能解析变量。单引号会把${selectStartValue}当作普通字符串直接拼接,导致请求的URL是无效的https://api.frankfurter.app/latest?from=${selectStartValue}`,而非替换成实际的货币代码。
修复步骤
1. 修正URL的模板字符串写法
把单引号替换为反引号,即可正确嵌入selectStartValue:
componentDidMount () { let { selectStartValue } = this.state; // 用反引号替换单引号 let listApi = `https://api.frankfurter.app/latest?from=${selectStartValue}` // ... 其余代码不变 }
2. 补充下拉框切换时的重新请求逻辑
当前代码仅在组件挂载时请求一次API,用户切换下拉框的货币选项后,汇率数据不会自动更新。需添加componentDidUpdate生命周期函数,监听selectStartValue的变化并重新发起请求:
componentDidUpdate(prevProps, prevState) { // 当selectStartValue发生变化时,重新请求汇率数据 if (prevState.selectStartValue !== this.state.selectStartValue) { const listApi = `https://api.frankfurter.app/latest?from=${this.state.selectStartValue}`; fetch(listApi) .then(checkStatus) .then(json) .then((data) => { this.setState({ rates: data.rates }); }) .catch((error) => { this.setState({ error: error.message }); console.log(error); }); } }
可选优化:提取请求逻辑为独立方法
为避免代码重复,可将汇率请求逻辑提取为单独方法,在componentDidMount和componentDidUpdate中复用:
fetchExchangeRates = (baseCurrency) => { const listApi = `https://api.frankfurter.app/latest?from=${baseCurrency}`; fetch(listApi) .then(checkStatus) .then(json) .then((data) => { this.setState({ rates: data.rates }); }) .catch((error) => { this.setState({ error: error.message }); console.log(error); }); } componentDidMount () { const { selectStartValue } = this.state; const currencyApi = 'https://api.frankfurter.app/currencies'; // 请求货币列表 fetch(currencyApi) .then(checkStatus) .then(json) .then((data) => { this.setState({ currencies: data }); }) .catch((error) => { this.setState({ error: error.message }); console.log(error); }); // 请求初始汇率 this.fetchExchangeRates(selectStartValue); } componentDidUpdate(prevProps, prevState) { if (prevState.selectStartValue !== this.state.selectStartValue) { this.fetchExchangeRates(this.state.selectStartValue); } }
内容的提问来源于stack exchange,提问作者AtomicCow
相关产品推荐
相关产品推荐

