几天前,我问了一个关于Laravel的问题,但是现在我将使用Nodejs和React进行拍摄。主要目标是:
为此,我想创建一个具有访存功能的文件,以备后用。有没有一种方法可以在文件中设置获取功能并重用它?
import React, { Component } from 'react';
import { fetch_function } from './fetch_file';
class App extends Component {
constructor(props) {
super(props);
this.state = {
Items: [],
is_loaded: false,
}
url = "http://localhost:4000";
this.fetch_function(url, this.state, "Items");
}
componentDidMount() {
}
render() {
var { is_loaded, Items} = this.state;
const options_select_items = Items.map((Item, id) => {
return ({ value: Item.id, label: Item.Name })
})
return (
<Form>
<Form.Group as={Row} controlId="formHorizontalClientes">
<Form.Label column sm={3}>
Cliente
</Form.Label>
<Col sm={9}>
<Select
closeMenuOnSelect={true}
defaultValue={[system_default[0]]}
isMulti
options={options_select_items}
/>
</Col>
</Form.Group>
</Form>
);
}
}
export default App;
这是提取文件
const fetch_function = (url, setState, param) => {
fetch(url)
.then(response => {
if (!response.ok) {
throw Error("Network failure")
}
return response;
})
.then(res => res.json())
.then(data => {
setState({
[param]: data
})
})
;
}
module.exports.fetch_function = fetch_function ;
是的,这是可能的并且非常可取,尤其是在您的项目不断发展的情况下。
我建议使用axios,因为它会自动返回JSON,并且比获取API更易于使用。
我也不建议更改该文件中的状态,因为在维护和调试代码时这将成为噩梦。
创建fetch.js
(或任何您想调用的名称)
import axios from 'axios';
const apiBaseURL = 'www.whatever.com'
export const GET = url => {
return axios.get(`${apiBaseURL}/${url}`);
}
// if need for headers etc.
const headers = 'some headers';
export const POST = (url, data) => {
return axios(`${apiBaseURL}/${url}`, {
method: 'POST',
headers,
data,
});
}
在react组件中:
导入文件在顶部:
import { GET, POST } from './fetch.js';
在组件方法中:
async getData(apiEndpoint) {
const { data: Items } = await GET(apiEndpoint);
if (Items) {
// Set data to state
this.setState({ Items });
}
else {
// error
}
}
同样也可以通过普通的获取API来实现。