跨反应组件使用自定义 api 客户端的惯用方法是什么?



我的前端应用程序包含ApiClient类,该类隐藏了与我的服务器进行http通信的详细信息。这是一个简单的TypeScript类,将axios客户端作为私有字段。

我面临着在根组件初始化客户端并将其传递给一些孩子的疑问。

此时此刻,我在根组件中启动我的客户端,作为构造函数中的简单js字段:

constructor() {
super()
... // init state here 
... // some initializations like this.handler = this.handler.bind(this)
this.apiClient = new ApiClient()
}

一些子组件也依赖于apiClient(例如,登录组件应该向登录端点发送请求,editModal组件通过id发送更新实体的请求(。现在我通过apiClient作为道具:

<Login show={this.state.show}
handleModalClose={this.handleModalClose}
handleSuccessfulLogin={this.handleSuccessfulLogin}
httpClient={this.apiClient}
/> }
...
<EditModal
httpClient={this.apiClient}
...
/>

将其传递给组件的惯用方法是什么?将客户端作为道具传递是否正确?如果我正确理解react文档,道具和状态将用于渲染,这对我来说有点困惑

如果你的api客户端不依赖于组件中的任何道具/状态,最好的方法是单独初始化它,然后导入到你需要使用它的文件中:

// apiClient.js
export const apiClient = new ApiClient();
// component.js 
import {apiClient} from '../apiClient';

如果您需要在组件内部处理登录/注销,该组件在api客户端内部设置令牌,您可以添加loginlogout方法,这些方法将在客户端初始化后调用。由于您的应用程序中只有一个客户端实例,这些更改(登录和注销(将在所有使用客户端的组件中生效:

// Client.js
class ApiClient {
constructor() {
// do intance init stuff if needed
this.token = null;
}
login(token) {
this.token = token;
}
logout() {
this.token = null;
}
}

// apiClient.js
export const apiClient = new ApiClient();
// component.js 
import { apiClient } from '../apiClient';
const LoginPage = props => {
const handleLogin = () => {
const token = // get the token
apiClient.login(token);
}
}

// anotherComponent.js
const User = props => {
useEffect(() => {
apiClient.getUser()
}, [])
}

相关内容