如何将值渲染到屏幕上?

问题描述 投票:0回答:2

我试图将 showUserInfo 的结果显示在页面上。我该怎么做?我想知道我是否需要在代码的返回部分创建一些东西或者是否是其他东西?

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

export default function App() {

  const [counter, setCounter] = useState(0); 
  const [jsonData, setJsonData] = useState(""); // response 
  const [userInfos, setUserInfos] = useState([]);

  const getAPI = () => {
    axios.get('https://randomuser.me/api')
    .then(function ({ data }) {
      // handle success
      // console.log({ data });
      const stringifiedData = JSON.stringify(data); 
      setJsonData(stringifiedData); 
      showUserInfo(data); 
      console.log(data);
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
  }

  const showUserInfo = ({ results }) => {
    const {0: { name }} = results;
    const {first, last} = name; 
    
    return (<div>`${first} {last}` </div>)
  }

  return (
    <div className="App">
      <button onClick={getAPI}>Get API</button>
      {userInfos}
    </div>
  );
}``` 
reactjs
2个回答
1
投票

我想这就是你所需要的。

你可以在这里查看,我刚刚做了类似的东西,你可以通过一些调整来修改它。

获取用户信息的按钮

这是我正在测试的代码:

import "./styles.css";
import { useState, useEffect } from "react";
import axios from "axios";

let url = "https://randomuser.me/api";

export default function App() {
  const [counter, setCounter] = useState(0);
  const [userInfos, setUserInfos] = useState([]);

  const [jsonData, setJsonData] = useState("");
  const [userName, setUserName] = useState({});

  useEffect(() => {
    axios
      .get(url)
      .then((res) => {
        const stringifiedData = JSON.stringify(res.data);
        setJsonData(stringifiedData);
      })
      .catch((err) => console.log(err));
  });

  const updateUserInfo = () => {
    const data = JSON.parse(jsonData);
    const fullName = data.results[0].name;
    setUserName(fullName);
  };

  return (
    <div className="App">
      <button onClick={updateUserInfo}>Click to Update</button>
      <div className="user">
        {userName.first} {userName.last}
      </div>
    </div>
  );
}

我们首先使用

useEffect
来获取您需要的 JSON,然后我像您一样使用
setJsonData
为其设置状态。但是在
updateUserInfo
中,你需要将jsonData解析回来,这样我们才能正常使用它,因为当我们通过
useEffect
时,我们已经使用了
stringify
,所以它只是一个字符串,而不是像我们解析时那样的对象完成了,那么就变得容易了,它会有这样的结构,例如:
{title: "Mr", first: "Kadir", last: "Balaban"}
。我还创建了 1 个名为
userName
的状态来测试它。你可以试试。

React第一次渲染时的

{userName.first} {userName.last}
会有
undefined
值,所以React理解它并且不会渲染,所以每当我们点击按钮时,我们设置
fullName
,然后我们调用
fullName.first
fullName.last
,它会更新状态并将这些值渲染到屏幕上,因为现在 React 知道它不是
undefined
不再了。


0
投票
import React, { Component, useState } from 'react'
import UserDetailsArray from '../db.json'
import { Navigate } from 'react-router-dom'
interface State {
    userData: any[],
    name: string,
    email: string,
    phone: string,
    password: string,
    confirmPassword: string,
    address: string
    errors: {
        name: string,
        email: string,
        password: string,
        confirmPassword: string,
        phone: string
    },
    isSubmitting: boolean,
    redirect: string,
    selectedId: number
}
export default class UserList extends Component<{}, State> {
    state: State = {
        userData: [],
        name: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: '',
        address: '',
        errors: {
            name: '',
            email: '',
            password: '',
            confirmPassword: '',
            phone: ''
        },
        isSubmitting: false,
        redirect: '',
        selectedId: 0
    }
    formReset() {
        this.setState({ name: '', email: '', phone: '', password: '', confirmPassword: '', address: '' });
    }
    componentDidMount(): void {
        this.getUserList()
        // console.log(UserDetailsArray.userList, 'userList');

    }
    addUser = async () => {
        this.setState({ isSubmitting: true });
        const { name, email, password, confirmPassword, errors, phone, address } = this.state;
        if ((name === '' || email === '') || password != confirmPassword || phone === '' || password == '') {
            return;
        }
        let obj = {
            id: 0,
            name: name,
            phone: phone,
            email: email,
            password: password,
            address: address
        }
        let oldLength = UserDetailsArray.userList.length;
        let data = UserDetailsArray.userList;
        if (data.length == 0) {
            obj.id = 1;
        } else {
            let newId = data[data.length - 1]?.id + 1;
            obj.id = newId;
        }
        data.push(obj);
        UserDetailsArray.userList = data;
        this.setState({ userData: data })
        if (oldLength < UserDetailsArray.userList.length) {
            this.setState({ isSubmitting: false });

        }
        document.getElementById('btn-close')?.click()
    }
    getUserList = async () => {
        var data = UserDetailsArray.userList;
        // data.forEach((res:any)=>{
        //     this.setState({userData: [...this.state.userData, res]})
        // })
        // console.log(data, 'dta');

        this.setState({ userData: data })
    }
    setvalues = async (item: any) => {
        this.setState({ selectedId: item.id, name: item.name, phone: item.phone, email: item.email, password: item.password, confirmPassword: item.confirmPassword, address: item.address })
    }
    removeUser = async (id: number) => {
        const isConfirmed = window.confirm("Are you sure you want to delete this item?");
        if (isConfirmed) {
            let data = UserDetailsArray.userList.filter(x => x.id != id);
            UserDetailsArray.userList = data;
            this.setState({ userData: data })
        }
    }
    render() {
        if (this.state.redirect) {
            return <Navigate to={this.state.redirect} />
        }
        return (
            <div className='container-fluid'>
                <div className="row">
                    <div className="col-md-10 mt-3 text-end" >
                        <button className=' btn btn-info' title='Logout' onClick={(e) => this.setState({ redirect: '/signin' })}><i className="bi bi-box-arrow-left"></i></button>
                    </div>
                </div>
                <div className='container p-5'>
                    <div className="d-flex  justify-content-between mb-3">
                        <h1 className='mb-0'>User List</h1>
                        <button className="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#exampleModal" onClick={(e) => { this.setState({ isSubmitting: false }); this.formReset() }}>Add User</button>
                    </div>
                    <table className='table table-striped table-hover'>
                        <thead className="table-light">
                            <tr>
                                <th>#</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>phone</th>
                                <th>Address</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {this.state.userData.length > 0 ? this.state.userData?.map((user: any, i) => (
                                <tr key={i}>
                                    <td>{i + 1}</td>
                                    <td>{user.name}</td>
                                    <td>{user.email}</td>
                                    <td>{user.phone}</td>
                                    <td>{user.address}</td>
                                    <td><button className='me-2 border-0 fs-5' data-bs-toggle="modal" data-bs-target="#exampleModal" onClick={(e) => this.setvalues(user)} ><i className="bi bi-pencil-square"></i></button><button className=' border-0 fs-5' onClick={(e) => this.removeUser(user.id)}><i className="bi bi-trash"></i></button></td>
                                </tr>
                            )) :
                                <tr>
                                    <td colSpan={12}><div className="text-center text-danger">No Data Found
                                    </div> </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>

                <div className="modal fade" id="exampleModal" aria-labelledby="exampleModalLabel" aria-hidden="true">
                    <div className="modal-dialog">
                        <div className="modal-content">
                            <div className="modal-header">
                                <h1 className="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
                                <button type="button" id='btn-close' className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div className="modal-body">
                                <div className="col-md-12  p-3">
                                    <h1 className='text-center'>Sign Up</h1>
                                    <div className="row gy-3">
                                        <div className="col-md-12">
                                            <label htmlFor="email">Name</label>
                                            <input
                                                type="text"
                                                className={this.state.name.length == 0 && this.state.isSubmitting ? 'is-invalid form-control' : 'form-control'}
                                                value={this.state.name}
                                                onChange={(e) => this.setState({ name: e.target.value })}

                                            />
                                            {this.state.name.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your name</div> : <></>}
                                        </div>
                                        <div className="col-md-12">
                                            <label htmlFor="email">Phone</label>
                                            <input
                                                type="number"
                                                className={this.state.phone.length == 0 && this.state.isSubmitting ? 'is-invalid form-control' : 'form-control'}
                                                value={this.state.phone}
                                                onChange={(e) => this.setState({ phone: e.target.value })}
                                            />
                                            {this.state.phone.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your phone number</div> : <></>}
                                        </div>
                                        <div className="col-md-12">
                                            <label htmlFor="email">Email</label>
                                            <input
                                                type="email"
                                                className={this.state.email.length == 0 && this.state.isSubmitting ? 'is-invalid form-control' : 'form-control'}
                                                value={this.state.email}
                                                onChange={(e) => this.setState({ email: e.target.value })}
                                            />
                                            {this.state.email.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your email</div> : <></>}
                                        </div>
                                        <div className="col-md-12">
                                            <label htmlFor="password">Password</label>
                                            <input
                                                type="password"
                                                className={this.state.password.length == 0 && this.state.isSubmitting || (this.state.confirmPassword != this.state.password && this.state.password && this.state.isSubmitting) ? 'is-invalid form-control' : 'form-control'}
                                                value={this.state.password}
                                                onChange={(e) => this.setState({ password: e.target.value })}
                                            />
                                            {this.state.password.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your password</div> : <></>}
                                        </div>
                                        <div className="col-md-12">
                                            <label htmlFor="confirmPassword">Confirm Password</label>
                                            <input
                                                type="password"
                                                className={(this.state.confirmPassword.length == 0 && this.state.isSubmitting) || (this.state.confirmPassword != this.state.password && this.state.password && this.state.isSubmitting) ? 'is-invalid form-control' : 'form-control'}
                                                value={this.state.confirmPassword}
                                                onChange={(e) => this.setState({ confirmPassword: e.target.value })}
                                            />
                                            {this.state.confirmPassword.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your confirm password</div> : <></>}
                                            {this.state.confirmPassword != this.state.password && this.state.confirmPassword && this.state.password && this.state.isSubmitting ? <div className="text-danger">Password and confirm password must be same.</div> : <></>}
                                        </div>
                                        <div className="col-md-12">
                                            <label htmlFor="confirmPassword">Address</label>
                                            <input
                                                type="text"
                                                className='form-control'
                                                value={this.state.address}
                                                onChange={(e) => this.setState({ address: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="modal-footer">
                                <button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                <button type="submit" className='btn btn-primary ' onClick={this.addUser}>
                                    Save
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}
//signup
import React, { Component, useState } from 'react'
import { Navigate } from 'react-router-dom';
import UserDetailsArray from '../db.json'
interface State {
  name: string,
  email: string,
  phone: string,
  password: string,
  confirmPassword: string,
  address: string
  errors: {
    name: string,
    email: string,
    password: string,
    confirmPassword: string,
    phone: string
  },
  isSubmitting: boolean,
  redirect: string
}
export default class SignUp extends Component<{}, State> {
  state: State = {
    name: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: '',
    address: '',
    errors: {
      name: '',
      email: '',
      password: '',
      confirmPassword: '',
      phone: ''
    },
    isSubmitting: false,
    redirect: ''
  }
  componentDidMount(): void {

  }
  SignUp = async () => {
    this.setState({ isSubmitting: true });
    const { name, email, password, confirmPassword, errors, phone, address } = this.state;
    if ((name === '' || email === '') || password != confirmPassword || phone === '' || password == '') {
      return;
    }
    let obj = {
      id: 0,
      name: name,
      phone: phone,
      email: email,
      password: password,
      address: address
    }
    let oldLength = UserDetailsArray.userList.length;
    let data = UserDetailsArray.userList;
    if (data.length == 0) {
      obj.id = 1;
    } else {
      let newId = data[data.length - 1]?.id + 1;
      obj.id = newId;
    }
    data.push(obj);
    UserDetailsArray.userList = data;
    if (oldLength < UserDetailsArray.userList.length) {
      this.setState({ redirect: '/userlist' })
      this.setState({ isSubmitting: false });
    }
  }
  render() {
    if (this.state.redirect) {
      return <Navigate to={this.state.redirect} />
    }
    return (
      <>
        <div className="container-fluid">
          <div className="row justify-content-center mt-5">
            <div className="col-md-5 card p-3">
              <h1 className='text-center'>Sign Up</h1>
              <div className="row gy-3">
                <div className="col-md-12">
                  <label htmlFor="email">Name</label>
                  <input
                    type="text"
                    className={this.state.name.length == 0 && this.state.isSubmitting ? 'is-invalid form-control' : 'form-control'}
                    value={this.state.name}
                    onChange={(e) => this.setState({ name: e.target.value })}

                  />
                  {this.state.name.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your name</div> : <></>}
                </div>
                <div className="col-md-12">
                  <label htmlFor="email">Phone</label>
                  <input
                    type="number"
                    className={this.state.phone.length == 0 && this.state.isSubmitting ? 'is-invalid form-control' : 'form-control'}
                    value={this.state.phone}
                    onChange={(e) => this.setState({ phone: e.target.value })}
                  />
                  {this.state.phone.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your phone number</div> : <></>}
                </div>
                <div className="col-md-12">
                  <label htmlFor="email">Email</label>
                  <input
                    type="email"
                    className={this.state.email.length == 0 && this.state.isSubmitting ? 'is-invalid form-control' : 'form-control'}
                    value={this.state.email}
                    onChange={(e) => this.setState({ email: e.target.value })}
                  />
                  {this.state.email.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your email</div> : <></>}
                </div>
                <div className="col-md-12">
                  <label htmlFor="password">Password</label>
                  <input
                    type="password"
                    className={this.state.password.length == 0 && this.state.isSubmitting ? 'is-invalid form-control' : 'form-control'}
                    value={this.state.password}
                    onChange={(e) => this.setState({ password: e.target.value })}
                  />
                  {this.state.password.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your password</div> : <></>}
                </div>
                <div className="col-md-12">
                  <label htmlFor="confirmPassword">Confirm Password</label>
                  <input
                    type="password"
                    className={this.state.confirmPassword.length == 0 && this.state.isSubmitting ? 'is-invalid form-control' : 'form-control'}
                    value={this.state.confirmPassword}
                    onChange={(e) => this.setState({ confirmPassword: e.target.value })}
                  />
                  {this.state.confirmPassword.length == 0 && this.state.isSubmitting ? <div className="text-danger">Please enter your confirm password</div> : <></>}
                  {this.state.confirmPassword != this.state.password && this.state.password && this.state.confirmPassword && this.state.isSubmitting ? <div className="text-danger">Password and confirm password must be same.</div> : <></>}
                </div>
                <div className="col-md-12">
                  <label htmlFor="confirmPassword">Address</label>
                  <input
                    type="text"
                    className='form-control'
                    value={this.state.address}
                    onChange={(e) => this.setState({ address: e.target.value })}
                  />
                </div>

                <div className="col-md-12 text-center">
                  <button type="submit" className='btn btn-info me-3' onClick={(e) => this.setState({ redirect: '/signin' })}>
                    Sign In
                  </button>
                  <button type="submit" className='btn btn-primary ' onClick={this.SignUp}>
                    {/* {this.state.isSubmitting ? 'Submitting...' : ''} */}
                    Sign Up
                  </button>

                </div>
              </div>
            </div>
          </div>
        </div>

      </>
    )
  }
}
//signin
import React, { Component, useState } from 'react'
import { Navigate } from 'react-router-dom';
import UserDetailsArray from '../db.json'
interface State {
    password: string,
    email: string,
    errorMessage: string,
    redirect: string
}
{/* <style>
    
    .sign-in-container {
        max-width: 400px;
        margin: 50px auto;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 8px;
        background-color: #f9f9f9;
      }
      
      .sign-in-form {
        display: flex;
        flex-direction: column;
      }
      
      .input-group {
        margin-bottom: 15px;
      }
      
      .input-group label {
        font-weight: bold;
      }
      
      .input-group input {
        width: 100%;
        padding: 8px;
        margin-top: 5px;
        border: 1px solid #ccc;
        border-radius: 4px;
      }
      
      .error-message {
        color: red;
        font-size: 14px;
        margin-bottom: 10px;
      }
      
      .submit-button {
        padding: 10px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }
      
      .submit-button:hover {
        background-color: #0056b3;
      }
      
    </style> */}
export default class SignIn extends Component<{}, State> {

    state: State = {
        password: "",
        email: "",
        errorMessage: "",
        redirect: ""
    }
    constructor(props: {}) {
        super(props);
        // this.state = {
        //     password: "1234",
        //     email: "[email protected]",
        //     errorMessage: "",
        //     redirect: ""
        // };
    }
    componentDidMount(): void {

    }
    signIn = async () => {
        if (!this.state.email) {
            this.setState({ errorMessage: "Please enter your email." })
            return;
        }
        if (!this.state.password) {
            this.setState({ errorMessage: "Please enter your password." })
            return;
        }
        this.setState({ errorMessage: "" })
        let data = UserDetailsArray.userList;
        if (data.length > 0) {
            const user = data.find((item: any) => item.email == this.state.email && item.password == this.state.password);
            if (!user) {
                console.log(user, 'user')
                alert('Invalid User Details')
            } else {
                this.setState({ redirect: '/userlist' })
            }
        } else {
            this.setState({ errorMessage: "User not found." })
        }
    }
    render() {
        if (this.state.redirect) {
            return <Navigate to={this.state.redirect} />
        }
        return (
            <div className="sign-in-container container-fluid">
                <h2>Sign In</h2>
                <div className="sign-in-form" >
                    <div className="input-group">
                        <label htmlFor="email">Email</label>
                        <input
                            type="email"
                            id="email"
                            name="email"
                            value={this.state.email}
                            onChange={(e) => this.setState({ email: e.target.value })}
                            required
                        />
                    </div>
                    <div className="input-group">
                        <label htmlFor="password">Password</label>
                        <input
                            type="password"
                            id="password"
                            name="password"
                            value={this.state.password}
                            onChange={(e) => this.setState({ password: e.target.value })}
                            required
                        />
                    </div>
                    {this.state.errorMessage && <p className="error-message">{this.state.errorMessage}</p>}
                    <button type="submit" className="submit-button mb-2" onClick={this.signIn}>
                        Sign In
                    </button>``
                    <button type="submit" className="btn btn-success" onClick={(e) => this.setState({ redirect: '/signup' })}>
                        Sign Up
                    </button>
                </div>
            </div>
        )
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.