简体   繁体   English

如何在反应中的无状态组件中设置状态,多个对象的值?

[英]How to set State, multiple objects value in the stateless component in react?

I am using a stateless component and got value from the json file, When I fetch data using map from json file object, then it will store only last data in state not whole objects:我正在使用无状态组件并从 json 文件中获取值,当我使用 map 从 json 文件对象获取数据时,它将只存储状态中的最后数据而不是整个对象:

import React, { useState, useEffect} from 'react'
import usersInformation from '../assets/dataconfig/users.json'

const Login = () => {

const [userEmail, updateEmail] = useState([]);
const [userPassword, updatePassword] = useState([]);

   useEffect(function () {
   const getUserdata = () => {
        usersInformation.authorizedwebusers.map(item => {
            console.log(item);
            updateEmail([...userEmail, item.emailAddress]); // here store only last json data - shiv@gmail.com
            updatePassword([...userPassword, item.emailpassword])
        })
    }
    getUserdata();

}, [])

} }

My json save as users.json:我的json另存为users.json:

{
 "authorizedwebusers": [
    {
        "name": "Anil",
        "emailAddress": "anil@gmail.com",
        "emailpassword": "123"
    },
    {
      "name": "Lalit",
      "emailAddress": "lalit.kumar@gmail.com",
      "emailpassword": "123"
    },
    {
        "name": "Shiv",
        "emailAddress": "shiv@gmail.com",
        "emailpassword": "123"
    }
  ]
}

You are doing it wrong.你做错了。 setXyz() is not a synchronous action, it takes some time. setXyz() 不是同步操作,它需要一些时间。 You need to implement this in a different way.您需要以不同的方式实现这一点。 First calculate and then set values.首先计算,然后设置值。

 useEffect(function () { const getUserdata = () => { const emails = []; const passwords = []; usersInformation.authorizedwebusers.map(item => { console.log(item); emails.push(item.emailAddress); passwords.push(item.emailpassword); }); updateEmail([...userEmail, ...emails]); updatePassword([...userPassword, ...passwords]) } getUserdata(); }, [])

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM