当我输入搜索时,我的用户详细信息不是不呈现用户列表

my users details is not is not rendering users list when i type in search

还有一个错误 TypeError: Cannot destructure 属性 'handleShow' of 'object null' as it is null. 当我控制台日志时的输出是 公关 SearchModal.js:35 {用户名: "pr"} SearchModal.js:38 [{…}]0: {id: "602df77cea2b563d7ceda4ac", 用户名: "pratik", 电子邮件: "pratik@gmail.com"}长度: 1__proto_: 数组(0) 当我输入 p 时它也没有搜索它给出 searc:'' 并且当我添加 prat 然后搜索时:仅 'pra' 此外,它不呈现用户名只是检查 userdetails.map 它是控制台记录详细信息但不在页面上呈现

import React, { Component } from 'react';
import { SearchUser } from '../services/SearchService';
import {Modal} from 'react-bootstrap';

class SearchModal extends Component {
  constructor(props){
    super(props);
    this.state = {
        show: false,
        search: '',
        userdetails:[]
    }

    this.handleShow = this.handleShow.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.onTextboxChangeSearch = this.onTextboxChangeSearch.bind(this);
}
handleShow() {
    this.setState({ show: true })
}
handleClose(){
    this.setState({ show: false })
}

async onTextboxChangeSearch(event) {

  this.setState({
      search: event.target.value
  });
  let {search,userdetails} = this.state;
  console.log(search)


  const data = {username:search};
  console.log(data)
  let SearchStatus = await SearchUser(data);
  userdetails=SearchStatus.user
  console.log(userdetails);
}

render() {
    let {search,userdetails}= this.state;

    return (
       <div>
          <Modal show={this.state.show} onHide={this.handleClose}>
             <Modal.Header closeButton>
               <Modal.Title>
                 <input 
                  type="text" 
                  placeholder="Search.."
                  value={search}
                  onChange={this.onTextboxChangeSearch}
                 ></input>
               </Modal.Title>
             </Modal.Header>
             <Modal.Body>
               <h3>Users</h3>
               <div>
               <ul>
                {userdetails.map(element => {
                  <li>{element.username}</li>
                })}
              </ul>
               </div>
             </Modal.Body>
          </Modal>
        </div>
    )
  }
}
export default SearchModal;

仪表板

import React, { Component } from 'react';
import { Link,Redirect } from 'react-router-dom';
import UserService from "../services/userservice";
import SearchModal from './SearchModal'

export default class Dashboard extends Component{

    constructor(props) {
        super(props);
    
        this.state = {
            currentUser: UserService.getCurrentUser(),
            isLoading:false,
        };

        this.logOut = this.logOut.bind(this);
        this.onClick = this.onClick.bind(this);

    }

    logOut() {
        UserService.logout()
    }

    SearchModalRef = ({handleShow}) => {
        this.showModal = handleShow;
    }
    
    onClick = () => {
        this.showModal();
    }
     

    render(){
        const { currentUser ,isLoading } = this.state;
        console.log(currentUser)

        if (isLoading) {
            return (<div><p>Loading...</p></div>);
        }

        if(!currentUser){
            return(
                <div>
                    <Redirect  to='/login' />
                </div>
            )
        }
        else{
            return(
                <div>
                    <header>
                        <h1>Dashboard</h1>
                        {' '}
                        <div>
                            <Link to={`/dashboard/profile/:${currentUser.user._id}`}>Profile</Link>
                        </div>
                        {' '}
                        <div>
                            <Link to="/login" onClick={this.logOut}>LogOut</Link>
                        </div>
                        {' '}
                        
                        <SearchModal  ref={this.SearchModalRef} ></SearchModal>
                        <button type="button" onClick={this.onClick}>
                        Search
                        </button>
                    </header>
                    <div>

                    </div>
                </div>
            );
        }
    }
}

问题

it is not searching when i type p its giving searc:'' and when i add prat then search : 'pra' only

React 状态更新是异步的,并且在渲染周期之间进行批处理。这意味着当您将状态更新加入队列时,直到下一个渲染周期它才会可用。同一函数中对状态的任何进一步引用都将是当前渲染周期的状态值。

async onTextboxChangeSearch(event) {
  this.setState({
    search: event.target.value // <-- next state
  });
  let {search,userdetails} = this.state; // <-- still current state!
  console.log(search)

  const data = {username:search};
  console.log(data)
  let SearchStatus = await SearchUser(data);
  userdetails=SearchStatus.user
  console.log(userdetails);
}

解决方案

我建议将搜索逻辑分解到它自己的函数中,以便在状态更新时由 componentDidUpdate 生命周期方法调用。

onTextboxChangeSearch(event) {
  const { value } = event.target;
  this.setState({
    search: value // <-- (1) update state
  });
}


searchForUser = async () => { // <-- (3) refactored search function
  const { search, userdetails } = this.state;
  const data = { username: search };

  const { user } = await SearchUser(data);
  this.setState(prevState => ({
    userdetails: [...prevState.userdetails, user], // append user
  }));
}

componentDidUpdate(prevProps, prevState) {
  if (prevState.search !== this.state.search) {
    this.searchForUser(); // <-- (2) search state updated, do search for user
  }
}