简体   繁体   中英

How to setState, object value in the stateless component in react?

I am using a stateless component and got value from the API with Axios & useEffect(), then I have set one value in the state but I want to set response object in the state:

import React, { useState, useEffect } from "react";
import axios from 'axios';

export default function Login(props) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [userData, setUserData] = useState([]);

function validateForm() {
    return email.length > 0 && password.length > 0;
}

useEffect(()=>{
    axios.get(apiBaseUrl+'api/users')
        .then(response =>{
            // how to set my value: response.data.data
            setUserData(response.data.data);
            console.log(response.data.data);
        }, error => {
            console.log(error)
        })
},[])

setUserData is a function to update your userData value. The code below should do the trick


const [userData, setUserData] = useState({});

 useEffect(()=>{
    axios.get(apiBaseUrl+'api/users')
        .then(response =>{
            // how to set my value: response.data.data
            setUserData(response.data.data)
            console.log(response.data.data)
        }, error => {
            console.log(error)
        })
},[])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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