我正在开发一个 React/Electron 应用程序,我想在其中使用 Redux 存储中的数据来初始化我的 Axios 客户端。例如,用例是在首次加载应用程序时,用户输入一些信息,例如用户名。它被推送到 Redux 存储(并保存在 localStorage
中以供将来使用),然后在 axios 客户端的 baseURL
中用于后续网络请求。
问题是,我无法让 axios 与react-redux 和 connect()
函数一起使用。 Axios 的函数导出似乎被导出的 HOC 隐藏了,每当我调用它的函数之一时,我都会收到以下错误:
TypeError: _Client2.default.get is not a function
我的客户看起来像这样:
import axios from "axios";
import { connect } from "react-redux";
const Client = ({ init }) => {
return axios.create({
baseURL: `http://${init.ip}/api/${init.username}`
});
};
const mapStateToProps = state => {
return { init: state.init };
};
export default connect(
mapStateToProps,
{}
)(Client);
我在这里做错了什么?
最佳答案
在react-redux文档中https://react-redux.js.org/api/connect#connect-returns它说The return of connect() is a wrapper function that takes your component and returns a wrapper component with the additional props it injects.
所以它返回包装react组件的react组件。您的函数返回 axios 客户端,它不会渲染任何内容。
我更喜欢使用 Action 创建者并在那里进行 api 调用(因此我不传递 axios 客户端或其他)。但如果我决定这样做,我将在 reducer 内初始化 axios 客户端并保留在商店中。然后将其作为 props 传递给客户端。
const mapStateToProps = state => {
return { axios: state.axios };
};
关于javascript - 使用Redux状态初始化axios客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58577491/