几天前,我问了一个关于Laravel的问题,但现在我要尝试一下Nodejs并做出反应。主要目标是:
为此,我希望创建一个带有fetch函数的文件,供以后使用。是否有一种方法可以在文件中设置一个获取函数并重用它?
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;这是fetch_file
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 ;发布于 2020-03-18 21:48:07
是的,这是可能的,也是非常明智的,特别是当你的项目成长的时候。
我建议使用axios,因为它会自动返回JSON,并且比fetch 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,
});
}在反应部分:
导入顶部的文件:
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
}
}同样,也可以通过普通的fetch API来实现。
https://stackoverflow.com/questions/60747216
复制相似问题