我正在尝试使用 module.exports 创建一个“全局”函数,我可以在我的 React 项目中使用它来使用 Axios 进行 API 调用。
我尝试了以下...
import axios from 'axios';
module.exports = {
fetchApi: function (endPoint) {
var encodedURI = window.encodeURI('http://localhost:3001/' + endPoint);
return axios.get(encodeURI)
.then(function (response) {
return response.data
})
}
}
//call function in other components like this
componentDidMount () {
fetchApi.fetchApi(this.setState.endPoint)
.then(function (endPoint) {
console.log("API endpoint: " + endPoint)
})
}
Run Code Online (Sandbox Code Playgroud)
这将返回错误... 'fetchApi' 未定义 no-undef
我知道通常您可以使用导出默认值导入和导出组件,但我认为如果使用 module.export,则不需要这样做。
另外,如果我尝试像这样导入...
import fetchApi from '../../../utils/api'
Run Code Online (Sandbox Code Playgroud)
我收到以下错误...尝试导入错误:“../../../utils/api”不包含默认导出(作为“fetchApi”导入)。
任何帮助表示赞赏。谢谢。
编辑:
从 'axios' 导入 axios;
解决方案(编辑)...
api.js
const api …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 React Hooks 中的 [useState} 从下拉选择中获取文本值。我只得到值(数字)而不是文本。我已经复制了下面控制选择下拉列表的代码位。我在这里缺少什么?谢谢。
const [addrtype, setAddrType] = useState('Home')
function handleAddrTypeChange(e) {
setAddrType(e.target.value);
console.log(addrtype)
}
<select
defaultValue={addrtype}
onChange={handleAddrTypeChange}
className="browser-default custom-select">
<option selected value="1">Home</option>
<option value="2">Marketing</option>
<option value="3">Work</option>
<option value="3">Head Office</option>
</select>
Run Code Online (Sandbox Code Playgroud)