首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ReactJs为获取创建一个单独的文件

ReactJs为获取创建一个单独的文件
EN

Stack Overflow用户
提问于 2020-03-18 20:41:58
回答 1查看 3K关注 0票数 0

几天前,我问了一个关于Laravel的问题,但现在我要尝试一下Nodejs并做出反应。主要目标是:

  • 左栏4选择,
    • 取决于第一个选择,第二个将显示一些信息。
    • 表中包含来自selects的信息。

  • 在右边/中间,
    • 显示。

  • 在右下角/中间。
    • 带有标签的面板。(来自表中的单个对象的信息)。

为此,我希望创建一个带有fetch函数的文件,供以后使用。是否有一种方法可以在文件中设置一个获取函数并重用它?

代码语言:javascript
复制
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

代码语言:javascript
复制
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 ;
EN

Stack Overflow用户

回答已采纳

发布于 2020-03-18 21:48:07

是的,这是可能的,也是非常明智的,特别是当你的项目成长的时候。

我建议使用axios,因为它会自动返回JSON,并且比fetch API更容易使用。

我也不建议修改该文件中的状态,因为在维护和调试代码时,它将成为一场噩梦。

创建一个fetch.js (或您想称之为它的任何东西)

代码语言:javascript
复制
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,
    });
}

在反应部分:

导入顶部的文件:

代码语言:javascript
复制
import { GET, POST } from './fetch.js';

在分量法中:

代码语言:javascript
复制
async getData(apiEndpoint) {
    const { data: Items } = await GET(apiEndpoint);
    if (Items) {
      // Set data to state
      this.setState({ Items });
    }
    else {
      // error
    }
}

同样,也可以通过普通的fetch API来实现。

票数 3
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60747216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档