简体   繁体   English

使用 React 中的 useEffect 和 useState 钩子从获取请求中管理数组

[英]Manage array from get request using useEffect and useState hooks in React

I need help in managing some values from a GET request that returns me an array of values from reading a file inside the server.我需要帮助来管理来自 GET 请求的一些值,该请求通过读取服务器内部的文件返回一组值。 When loading the functional component I want send the request so I'm using useState and useEffect in my code like the following:加载功能组件时,我要发送请求,因此我在代码中使用 useState 和 useEffect ,如下所示:

import { useHttpClient } from '../shared/hooks/http-hook';

...

const Settings = () => {
    const { isLoading, error, sendRequest, clearError } = useHttpClient();
    const [loadedSettings, setLoadedSettings] = useState([]);
    
        useEffect(() => {
            const fetchSettings = async () => {
                try {
                    const responseData = await sendRequest(
                        'http://localhost/api/settings'
                    );
                    setLoadedSettings(responseData)
                } catch (err) { }
            };
            fetchSettings();
        }, []);

I need to do this to fill some inputs of my form with the values from the array I get from the request:我需要这样做以使用从请求中获得的数组中的值填充表单的一些输入:

    return (
            <React.Fragment>
                <ErrorModal error={error} onClear={clearError} />
                {isLoading && <LoadingSpinner asOverlay />}
                <form className="settings-form" onSubmit={settingsSubmitHandler}>
                    <div className="container">
                        <div className="row">
                            <div className="col">
                                <div className="form-group row">
                                    <div className="col-sm-12">
                                        <p>Database Connection:</p>
                                    </div>
                                </div>
                                <div className="form-group row">
                                    <div className="col-sm-12">
                                        <Input
                                            element="input"
                                            id="hostname"
                                            type="text"
                                            title="HOSTNAME"
                                            placeholder="HOST NAME"
                                            validators={[VALIDATOR_REQUIRE()]}
                                            errorText="Required."
                                            onInput={inputHandler}
                                        />
                                    </div>
                                </div>
                                <div className="form-group row">
                                <div className="col-sm-12">
                                    <Input
                                        element="input"
                                        id="username"
                                        type="text"
                                        title="USERNAME"
                                        placeholder="USERNAME"
                                        validators={[VALIDATOR_REQUIRE()]}
                                        errorText="Required."
                                        onInput={inputHandler}
                                    />
                                </div>
                            </div>
                            <div className="form-group row">
                                <div className="col-sm-12">
                                    <Input
                                        element="input"
                                        id="password"
                                        type="password"
                                        title="PASSWORD"
                                        placeholder="PASSWORD"
                                        validators={[VALIDATOR_REQUIRE()]}
                                        errorText="Required."
                                        onInput={inputHandler}
                                    />
                                </div>
                            </div>
    
    ...

If I console log:如果我控制台日志:

loadedSettings.map(elem => {
    console.log(elem)
}

It returns me all values from text file as expected.它按预期返回文本文件中的所有值。 How can I put every value in each input box?如何在每个输入框中输入每个值?

Thanks谢谢

you can try to render the form input elements inside the map function您可以尝试在 map function 中呈现表单输入元素

please let me know if this worked fine with you请让我知道这是否适合您


return (
..
loadedSettings.map(elem=>(
          <Input
            element="input"
            value={elem}
            id="hostname"
            type="text"
            title="HOSTNAME"
            placeholder="HOST NAME"
            validators={[VALIDATOR_REQUIRE()]}
            errorText="Required."
            onInput={inputHandler}
           />
))
)

I think, you can just replace this section我认为,您可以替换此部分

<div className="col-sm-12">
  <Input
    element="input"
    id="hostname"
    type="text"
    title="HOSTNAME"
    placeholder="HOST NAME"
    validators={[VALIDATOR_REQUIRE()]}
    errorText="Required."
    onInput={inputHandler}
  />
</div>;

with

{loadedSettings && loadedSettings.map((setting) => (
    <div className="col-sm-12">
        <Input
            element="input"
            id="hostname"
            type="text"
            title="HOSTNAME"
            placeholder="HOST NAME"
            validators={[VALIDATOR_REQUIRE()]}
            errorText="Required."
            onInput={inputHandler}
            value={setting}
        />
    </div>
)}

I solved with this {!isLoading && loadedSettings && ( and transformed array into an object so I can add in my input elements initialValue={loadedSettings.MYHOST} ecc..我解决了这个{!isLoading && loadedSettings && (并将数组转换为 object 所以我可以添加我的输入元素initialValue={loadedSettings.MYHOST} ecc..

{
   "MYHOST": "value1",
   "MYUSER": "value2",
   ....
   ....
}

Here the jsx code这里是jsx代码

return (
    <React.Fragment>
        <ErrorModal error={error} onClear={clearError} />
        {isLoading && <LoadingSpinner asOverlay />}
        {!isLoading && loadedSettings && (
            <form className="settings-form" onSubmit={settingsSubmitHandler}>
                <div className="container">
                    <div className="row">
                        <div className="col">
                            <div className="form-group row">
                                <div className="col-sm-12">
                                    <p>Database Connection:</p>
                                </div>
                            </div>
                            <div className="form-group row">
                                <div className="col-sm-12">
                                    <Input
                                        element="input"
                                        id="hostname"
                                        type="text"
                                        title="HOSTNAME"
                                        placeholder="HOST NAME"
                                        validators={[VALIDATOR_REQUIRE()]}
                                        errorText="Required."
                                        onInput={inputHandler}
                                        initialValue={loadedSettings.MYHOST}
                                        initialValid={true}
                                    />
                                </div>
                            </div>
                            <div className="form-group row">
                                <div className="col-sm-12">
                                    <Input
                                        element="input"
                                        id="username"
                                        type="text"
                                        title="USERNAME"
                                        placeholder="USERNAME"
                                        validators={[VALIDATOR_REQUIRE()]}
                                        errorText="Required."
                                        onInput={inputHandler}
                                        initialValue={loadedSettings.MYUSER}
                                        initialValid={true}
                                    />
                                </div>
                            </div>

                            ...
                            ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 React 更新二维数组并挂钩 useState 和 useEffect - Update 2d array using React and hooks useState and useEffect React Hooks useState useEffect 幻灯片 - React Hooks useState useEffect slideshow 在 React Hooks 中使用 useEffect 更新对象数组 - update array of objects using useEffect in React Hooks 如何测试useState和useEffect反应钩子 - How to test useState and useEffect react hooks React:使用 useEffect 和/或 useState 钩子混淆行为 - React: Confusing behavior with useEffect and/or useState hooks React Hooks 上的 useState 不更新数组 - useState on React Hooks not updating Array React Hooks useState 更新数组 - React Hooks useState updating an array 使用 React Hooks,使用“useState”和“useEffect”,有没有办法渲染一个状态直到状态有一个值? - Using React Hooks, using "useState" and "useEffect", is there a way to render a state waiting till the state has a value? React Hooks:在 useEffect 中使用 useState 不会在第一次渲染后立即设置状态 - React Hooks: using useState inside useEffect doesn't set the state immediately after first rendering 无法使用 microbundle 和 React 渲染自定义组件包中的 useState、useEffect 挂钩 - Unable to render useState, useEffect hooks in custom component package using microbundle & React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM